HomeRootView.swift 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  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 { 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 + " " +
  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 bg = eventualBG as Decimal
  365. HStack {
  366. Image(systemName: "arrow.right.circle")
  367. .font(.callout).fontWeight(.bold)
  368. Text(
  369. Formatter.decimalFormatterWithTwoFractionDigits.string(
  370. from: (
  371. state.units == .mmolL ? bg
  372. .asMmolL : bg
  373. ) as NSNumber
  374. )!
  375. ).font(.callout).fontWeight(.bold).fontDesign(.rounded)
  376. }
  377. // aligns the evBG icon exactly with the first pixel of loop status icon
  378. .padding(.leading, 12)
  379. } else {
  380. HStack {
  381. Image(systemName: "arrow.right.circle")
  382. .font(.callout).fontWeight(.bold)
  383. Text("--")
  384. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  385. }
  386. }
  387. }
  388. }
  389. @ViewBuilder func mealPanel(_: GeometryProxy) -> some View {
  390. HStack {
  391. HStack {
  392. Image(systemName: "syringe.fill")
  393. .font(.callout)
  394. .foregroundColor(Color.insulin)
  395. Text(
  396. (
  397. Formatter.decimalFormatterWithTwoFractionDigits
  398. .string(from: (state.enactedAndNonEnactedDeterminations.first?.iob ?? 0) as NSNumber) ?? "0"
  399. ) +
  400. String(localized: " U", comment: "Insulin unit")
  401. )
  402. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  403. }
  404. Spacer()
  405. HStack {
  406. Image(systemName: "fork.knife")
  407. .font(.callout)
  408. .foregroundColor(.loopYellow)
  409. Text(
  410. (
  411. Formatter.decimalFormatterWithTwoFractionDigits.string(
  412. from: NSNumber(value: state.enactedAndNonEnactedDeterminations.first?.cob ?? 0)
  413. ) ?? "0"
  414. ) +
  415. String(localized: " g", comment: "gram of carbs")
  416. )
  417. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  418. }
  419. Spacer()
  420. HStack {
  421. if state.pumpSuspended {
  422. Text("Pump suspended")
  423. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  424. .foregroundColor(.loopGray)
  425. } else if let tempBasalString = tempBasalString {
  426. Image(systemName: "drop.circle")
  427. .font(.callout)
  428. .foregroundColor(.insulinTintColor)
  429. if tempBasalString.count > 5 {
  430. Text(tempBasalString)
  431. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  432. .lineLimit(1)
  433. .minimumScaleFactor(0.85)
  434. .truncationMode(.tail)
  435. .allowsTightening(true)
  436. } else {
  437. // Short strings can just display normally
  438. Text(tempBasalString).font(.callout).fontWeight(.bold).fontDesign(.rounded)
  439. }
  440. } else {
  441. Image(systemName: "drop.circle")
  442. .font(.callout)
  443. .foregroundColor(.insulinTintColor)
  444. Text("No Data")
  445. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  446. }
  447. }
  448. if state.totalInsulinDisplayType == .totalDailyDose {
  449. Spacer()
  450. Text(
  451. "TDD: " +
  452. (
  453. Formatter.decimalFormatterWithTwoFractionDigits
  454. .string(from: (state.fetchedTDDs.first?.totalDailyDose ?? 0) as NSNumber) ??
  455. "0"
  456. ) +
  457. String(localized: " U", comment: "Insulin unit")
  458. )
  459. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  460. } else {
  461. Spacer()
  462. HStack {
  463. Text(
  464. "TINS: \(state.roundedTotalBolus)" +
  465. String(localized: " U", comment: "Unit in number of units delivered (keep the space character!)")
  466. )
  467. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  468. .onChange(of: state.hours) {
  469. state.roundedTotalBolus = state.calculateTINS()
  470. }
  471. .onAppear {
  472. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  473. state.roundedTotalBolus = state.calculateTINS()
  474. }
  475. }
  476. }
  477. }
  478. }.padding(.horizontal, 10)
  479. }
  480. @ViewBuilder func adjustmentsOverrideView(_ overrideString: String) -> some View {
  481. Group {
  482. Image(systemName: "clock.arrow.2.circlepath")
  483. .font(.title2)
  484. .foregroundStyle(Color.primary, Color.purple)
  485. VStack(alignment: .leading) {
  486. Text(latestOverride.first?.name ?? String(localized: "Custom Override"))
  487. .font(.subheadline)
  488. .frame(alignment: .leading)
  489. Text(overrideString)
  490. .font(.caption)
  491. }
  492. }
  493. .onTapGesture {
  494. selectedTab = 2
  495. }
  496. }
  497. @ViewBuilder func adjustmentsTempTargetView(_ tempTargetString: String) -> some View {
  498. Group {
  499. Image(systemName: "target")
  500. .font(.title2)
  501. .foregroundStyle(Color.loopGreen)
  502. VStack(alignment: .leading) {
  503. Text(latestTempTarget.first?.name ?? String(localized: "Temp Target"))
  504. .font(.subheadline)
  505. Text(tempTargetString)
  506. .font(.caption)
  507. }
  508. }
  509. .onTapGesture {
  510. selectedTab = 2
  511. }
  512. }
  513. @ViewBuilder func adjustmentsCancelView(_ cancelAction: @escaping () -> Void) -> some View {
  514. Image(systemName: "xmark.app")
  515. .font(.title)
  516. .onTapGesture {
  517. cancelAction()
  518. }
  519. }
  520. @ViewBuilder func adjustmentsCancelTempTargetView() -> some View {
  521. Image(systemName: "xmark.app")
  522. .font(.title)
  523. .confirmationDialog(
  524. "Stop the Temp Target \"\(latestTempTarget.first?.name ?? "")\"?",
  525. isPresented: $isConfirmStopTempTargetShown,
  526. titleVisibility: .visible
  527. ) {
  528. Button("Stop", role: .destructive) {
  529. Task {
  530. guard let objectID = latestTempTarget.first?.objectID else { return }
  531. await state.cancelTempTarget(withID: objectID)
  532. }
  533. }
  534. Button("Cancel", role: .cancel) {}
  535. }
  536. .padding(.trailing, 8)
  537. .onTapGesture {
  538. if !latestTempTarget.isEmpty {
  539. isConfirmStopTempTargetShown = true
  540. }
  541. }
  542. }
  543. @ViewBuilder func adjustmentsCancelOverrideView() -> some View {
  544. Image(systemName: "xmark.app")
  545. .font(.title)
  546. .confirmationDialog(
  547. "Stop the Override \"\(latestOverride.first?.name ?? "")\"?",
  548. isPresented: $isConfirmStopOverridePresented,
  549. titleVisibility: .visible
  550. ) {
  551. Button("Stop", role: .destructive) {
  552. Task {
  553. guard let objectID = latestOverride.first?.objectID else { return }
  554. await state.cancelOverride(withID: objectID)
  555. }
  556. }
  557. Button("Cancel", role: .cancel) {}
  558. }
  559. .padding(.trailing, 8)
  560. .onTapGesture {
  561. if !latestOverride.isEmpty {
  562. isConfirmStopOverridePresented = true
  563. }
  564. }
  565. }
  566. @ViewBuilder func noActiveAdjustmentsView() -> some View {
  567. Group {
  568. VStack {
  569. Text("No Active Adjustment")
  570. .font(.subheadline)
  571. .frame(maxWidth: .infinity, alignment: .leading)
  572. Text("Profile at 100 %")
  573. .font(.caption)
  574. .frame(maxWidth: .infinity, alignment: .leading)
  575. }.padding(.leading, 10)
  576. Spacer()
  577. /// to ensure the same position....
  578. Image(systemName: "xmark.app")
  579. .font(.title)
  580. // clear color for the icon
  581. .foregroundStyle(Color.clear)
  582. }.onTapGesture {
  583. selectedTab = 2
  584. }
  585. }
  586. @ViewBuilder func adjustmentView(geo: GeometryProxy) -> some View {
  587. // let background = colorScheme == .dark ? Material.ultraThinMaterial.opacity(0.5) : Color.black.opacity(0.2)
  588. ZStack {
  589. /// rectangle as background
  590. RoundedRectangle(cornerRadius: 15)
  591. .fill(
  592. (overrideString != nil || tempTargetString != nil) ?
  593. (
  594. colorScheme == .dark ?
  595. Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) :
  596. Color.insulin.opacity(0.1)
  597. ) : Color.clear // Use clear and add the Material in the background
  598. )
  599. .background(colorScheme == .dark ? Color.chart.opacity(0.25) : Color.black.opacity(0.075))
  600. .clipShape(RoundedRectangle(cornerRadius: 15))
  601. .frame(height: geo.size.height * 0.08)
  602. .shadow(
  603. color: (overrideString != nil || tempTargetString != nil) ?
  604. (
  605. colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  606. Color.black.opacity(0.33)
  607. ) : Color.clear,
  608. radius: 3
  609. )
  610. HStack {
  611. if let overrideString = overrideString, let tempTargetString = tempTargetString {
  612. HStack {
  613. adjustmentsOverrideView(overrideString)
  614. Spacer()
  615. Divider()
  616. .frame(height: geo.size.height * 0.05)
  617. .padding(.horizontal, 2)
  618. adjustmentsTempTargetView(tempTargetString)
  619. Spacer()
  620. adjustmentsCancelView({
  621. if !latestTempTarget.isEmpty, !latestOverride.isEmpty {
  622. showCancelConfirmDialog = true
  623. } else if !latestOverride.isEmpty {
  624. showCancelAlert = true
  625. } else if !latestTempTarget.isEmpty {
  626. showCancelAlert = true
  627. }
  628. })
  629. }
  630. } else if let overrideString = overrideString {
  631. adjustmentsOverrideView(overrideString)
  632. Spacer()
  633. adjustmentsCancelOverrideView()
  634. } else if let tempTargetString = tempTargetString {
  635. HStack {
  636. adjustmentsTempTargetView(tempTargetString)
  637. Spacer()
  638. adjustmentsCancelTempTargetView()
  639. }
  640. } else {
  641. noActiveAdjustmentsView()
  642. }
  643. }.padding(.horizontal, 10)
  644. .confirmationDialog("Adjustment to Stop", isPresented: $showCancelConfirmDialog) {
  645. Button("Stop Override", role: .destructive) {
  646. Task {
  647. guard let objectID = latestOverride.first?.objectID else { return }
  648. await state.cancelOverride(withID: objectID)
  649. }
  650. }
  651. Button("Stop Temp Target", role: .destructive) {
  652. Task {
  653. guard let objectID = latestTempTarget.first?.objectID else { return }
  654. await state.cancelTempTarget(withID: objectID)
  655. }
  656. }
  657. Button("Stop All Adjustments", role: .destructive) {
  658. Task {
  659. guard let overrideObjectID = latestOverride.first?.objectID else { return }
  660. await state.cancelOverride(withID: overrideObjectID)
  661. guard let tempTargetObjectID = latestTempTarget.first?.objectID else { return }
  662. await state.cancelTempTarget(withID: tempTargetObjectID)
  663. }
  664. }
  665. } message: {
  666. Text("Select Adjustment")
  667. }
  668. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  669. }
  670. @ViewBuilder func bolusProgressBar(_ progress: Decimal) -> some View {
  671. GeometryReader { geo in
  672. RoundedRectangle(cornerRadius: 15)
  673. .frame(height: 6)
  674. .foregroundColor(.clear)
  675. .background(
  676. LinearGradient(colors: [
  677. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  678. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  679. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  680. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  681. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  682. ], startPoint: .leading, endPoint: .trailing)
  683. .mask(alignment: .leading) {
  684. RoundedRectangle(cornerRadius: 15)
  685. .frame(width: geo.size.width * CGFloat(progress))
  686. }
  687. )
  688. }
  689. }
  690. @ViewBuilder func bolusView(geo: GeometryProxy, _ progress: Decimal) -> some View {
  691. /// ensure that state.lastPumpBolus has a value, i.e. there is a last bolus done by the pump and not an external bolus
  692. /// - TRUE: show the pump bolus
  693. /// - FALSE: do not show a progress bar at all
  694. if let bolusTotal = state.lastPumpBolus?.bolus?.amount {
  695. let bolusFraction = progress * (bolusTotal as Decimal)
  696. let bolusString =
  697. (bolusProgressFormatter.string(from: bolusFraction as NSNumber) ?? "0")
  698. + String(localized: " of ", comment: "Bolus string partial message: 'x U of y U' in home view") +
  699. (Formatter.decimalFormatterWithTwoFractionDigits.string(from: bolusTotal as NSNumber) ?? "0")
  700. + String(localized: " U", comment: "Insulin unit")
  701. ZStack {
  702. /// rectangle as background
  703. RoundedRectangle(cornerRadius: 15)
  704. .fill(
  705. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color
  706. .insulin
  707. .opacity(0.2)
  708. )
  709. .clipShape(RoundedRectangle(cornerRadius: 15))
  710. .frame(height: geo.size.height * 0.08)
  711. .shadow(
  712. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  713. Color.black.opacity(0.33),
  714. radius: 3
  715. )
  716. /// actual bolus view
  717. HStack {
  718. Image(systemName: "cross.vial.fill")
  719. .font(.system(size: 25))
  720. Spacer()
  721. VStack {
  722. Text("Bolusing")
  723. .font(.subheadline)
  724. .frame(maxWidth: .infinity, alignment: .leading)
  725. Text(bolusString)
  726. .font(.caption)
  727. .frame(maxWidth: .infinity, alignment: .leading)
  728. }.padding(.leading, 5)
  729. Spacer()
  730. Button {
  731. state.showProgressView()
  732. state.cancelBolus()
  733. } label: {
  734. Image(systemName: "xmark.app")
  735. .font(.system(size: 25))
  736. }
  737. }.padding(.horizontal, 10)
  738. .padding(.trailing, 8)
  739. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  740. .overlay(alignment: .bottom) {
  741. // Use a geo-based offset here to position progress bar independent of device size
  742. let offset = geo.size.height * 0.0725
  743. bolusProgressBar(progress).padding(.horizontal, 18)
  744. .offset(y: offset)
  745. }.clipShape(RoundedRectangle(cornerRadius: 15))
  746. }
  747. }
  748. @ViewBuilder func alertSafetyNotificationsView(geo: GeometryProxy) -> some View {
  749. ZStack {
  750. /// rectangle as background
  751. RoundedRectangle(cornerRadius: 15)
  752. .fill(
  753. Color(
  754. red: 0.9,
  755. green: 0.133333333,
  756. blue: 0.2156862745
  757. )
  758. )
  759. .clipShape(RoundedRectangle(cornerRadius: 15))
  760. .frame(height: geo.size.height * safeAreaSize)
  761. .coordinateSpace(name: "alertSafetyNotificationsView")
  762. .shadow(
  763. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  764. Color.black.opacity(0.33),
  765. radius: 3
  766. )
  767. HStack {
  768. Spacer()
  769. VStack {
  770. Text("⚠️ Safety Notifications are OFF")
  771. .font(.headline)
  772. .fontWeight(.bold)
  773. .fontDesign(.rounded)
  774. .foregroundStyle(.white.gradient)
  775. .frame(maxWidth: .infinity, alignment: .leading)
  776. Text("Fix now by turning Notifications ON.")
  777. .font(.footnote)
  778. .fontDesign(.rounded)
  779. .foregroundStyle(.white.gradient)
  780. .frame(maxWidth: .infinity, alignment: .leading)
  781. }.padding(.leading, 5)
  782. Spacer()
  783. Image(systemName: "chevron.right").foregroundColor(.white)
  784. .font(.headline)
  785. }.padding(.horizontal, 10)
  786. .padding(.trailing, 8)
  787. .onTapGesture {
  788. UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
  789. }
  790. }.padding(.horizontal, 10)
  791. .padding(.top, 0)
  792. }
  793. @ViewBuilder func mainViewElements(_ geo: GeometryProxy) -> some View {
  794. VStack(spacing: 0) {
  795. ZStack {
  796. /// glucose bobble
  797. glucoseView
  798. /// right panel with loop status and evBG
  799. HStack {
  800. Spacer()
  801. rightHeaderPanel(geo)
  802. }.padding(.trailing, 20)
  803. /// left panel with pump related info
  804. HStack {
  805. pumpView
  806. Spacer()
  807. }.padding(.leading, 20)
  808. }
  809. .padding(.top, 10)
  810. .safeAreaInset(edge: .top, spacing: 0) {
  811. if notificationsDisabled {
  812. alertSafetyNotificationsView(geo: geo)
  813. }
  814. if let badgeImage = state.pumpStatusBadgeImage, let badgeColor = state.pumpStatusBadgeColor {
  815. pumpTimezoneView(badgeImage, badgeColor)
  816. .padding(.horizontal, 20)
  817. }
  818. }
  819. mealPanel(geo).padding(.top, UIDevice.adjustPadding(min: nil, max: 30))
  820. .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 20))
  821. mainChart(geo: geo)
  822. HStack {
  823. tappableButton(
  824. buttonColor: (colorScheme == .dark ? Color.white : Color.black).opacity(0.8),
  825. label: String(localized: "Stats", comment: "Stats icon in main view"),
  826. iconString: statsIconString,
  827. action: { state.showModal(for: .statistics) }
  828. )
  829. Spacer()
  830. timeIntervalButtons.padding(.top, UIDevice.adjustPadding(min: 0, max: 10))
  831. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: 10))
  832. Spacer()
  833. tappableButton(
  834. buttonColor: (colorScheme == .dark ? Color.white : Color.black).opacity(0.8),
  835. label: String(localized: "Info", comment: "Info icon in main view"),
  836. iconString: "info",
  837. action: { state.isLegendPresented.toggle() }
  838. )
  839. }.padding([.horizontal, .bottom])
  840. if let progress = state.bolusProgress {
  841. bolusView(geo: geo, progress)
  842. .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  843. } else {
  844. adjustmentView(geo: geo).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  845. }
  846. }
  847. .background(appState.trioBackgroundColor(for: colorScheme))
  848. .onReceive(
  849. resolver.resolve(AlertPermissionsChecker.self)!.$notificationsDisabled,
  850. perform: {
  851. if notificationsDisabled != $0 {
  852. notificationsDisabled = $0
  853. if notificationsDisabled {
  854. debug(.default, "notificationsDisabled")
  855. }
  856. }
  857. }
  858. )
  859. }
  860. @ViewBuilder func mainView() -> some View {
  861. GeometryReader { geo in
  862. mainViewElements(geo)
  863. }
  864. .onChange(of: state.hours) {
  865. highlightButtons()
  866. }
  867. .onAppear {
  868. configureView {
  869. highlightButtons()
  870. }
  871. }
  872. .navigationTitle("Home")
  873. .navigationBarHidden(true)
  874. .ignoresSafeArea(.keyboard)
  875. .blur(radius: state.isLoopStatusPresented ? 3 : 0)
  876. .sheet(isPresented: $state.isLoopStatusPresented) {
  877. LoopStatusView(state: state)
  878. }
  879. .sheet(isPresented: $state.isLegendPresented) {
  880. ChartLegendView(state: state)
  881. }
  882. // PUMP RELATED
  883. .confirmationDialog("Pump Model", isPresented: $showPumpSelection) {
  884. Button("Medtronic") { state.addPump(.minimed) }
  885. Button("Omnipod Eros") { state.addPump(.omnipod) }
  886. Button("Omnipod Dash") { state.addPump(.omnipodBLE) }
  887. Button("Dana(RS/-i)") { state.addPump(.dana) }
  888. Button("Pump Simulator") { state.addPump(.simulator) }
  889. } message: { Text("Select Pump Model") }
  890. .sheet(isPresented: $state.shouldDisplayPumpSetupSheet) {
  891. if let pumpManager = state.provider.apsManager.pumpManager {
  892. PumpConfig.PumpSettingsView(
  893. pumpManager: pumpManager,
  894. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  895. completionDelegate: state,
  896. setupDelegate: state
  897. )
  898. } else {
  899. PumpConfig.PumpSetupView(
  900. pumpType: state.setupPumpType,
  901. pumpInitialSettings: PumpConfig.PumpInitialSettings.default,
  902. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  903. completionDelegate: state,
  904. setupDelegate: state
  905. )
  906. }
  907. }
  908. // CGM RELATED
  909. .confirmationDialog("CGM Model", isPresented: $showCGMSelection) {
  910. cgmSelectionButtons
  911. } message: {
  912. Text("Select CGM Model")
  913. }
  914. .sheet(isPresented: $state.shouldDisplayCGMSetupSheet) {
  915. switch state.cgmCurrent.type {
  916. case .enlite,
  917. .nightscout,
  918. .none,
  919. .simulator,
  920. .xdrip:
  921. CGMSettings.CustomCGMOptionsView(
  922. resolver: self.resolver,
  923. state: state.cgmStateModel,
  924. cgmCurrent: state.cgmCurrent,
  925. deleteCGM: state.deleteCGM
  926. )
  927. case .plugin:
  928. if let fetchGlucoseManager = state.fetchGlucoseManager,
  929. let cgmManager = fetchGlucoseManager.cgmManager,
  930. state.cgmCurrent.type == fetchGlucoseManager.cgmGlucoseSourceType,
  931. state.cgmCurrent.id == fetchGlucoseManager.cgmGlucosePluginId
  932. {
  933. CGMSettings.CGMSettingsView(
  934. cgmManager: cgmManager,
  935. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  936. unit: state.settingsManager.settings.units,
  937. completionDelegate: state
  938. )
  939. } else {
  940. CGMSettings.CGMSetupView(
  941. CGMType: state.cgmCurrent,
  942. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  943. unit: state.settingsManager.settings.units,
  944. completionDelegate: state,
  945. setupDelegate: state,
  946. pluginCGMManager: self.state.pluginCGMManager
  947. )
  948. }
  949. }
  950. }
  951. }
  952. @ViewBuilder func tabBar() -> some View {
  953. ZStack(alignment: .bottom) {
  954. TabView(selection: $selectedTab) {
  955. let carbsRequiredBadge: String? = {
  956. guard let carbsRequired = state.enactedAndNonEnactedDeterminations.first?.carbsRequired,
  957. state.showCarbsRequiredBadge
  958. else {
  959. return nil
  960. }
  961. let carbsRequiredDecimal = Decimal(carbsRequired)
  962. if carbsRequiredDecimal > state.settingsManager.settings.carbsRequiredThreshold {
  963. let numberAsNSNumber = NSDecimalNumber(decimal: carbsRequiredDecimal)
  964. return (Formatter.decimalFormatterWithTwoFractionDigits.string(from: numberAsNSNumber) ?? "") + " g"
  965. }
  966. return nil
  967. }()
  968. NavigationStack { mainView() }
  969. .tabItem { Label("Main", systemImage: "chart.xyaxis.line") }
  970. .badge(carbsRequiredBadge).tag(0)
  971. NavigationStack { DataTable.RootView(resolver: resolver) }
  972. .tabItem { Label("History", systemImage: historySFSymbol) }.tag(1)
  973. Spacer()
  974. NavigationStack { Adjustments.RootView(resolver: resolver) }
  975. .tabItem {
  976. Label(
  977. "Adjustments",
  978. systemImage: "slider.horizontal.2.gobackward"
  979. ) }.tag(2)
  980. NavigationStack(path: self.$settingsPath) {
  981. Settings.RootView(resolver: resolver) }
  982. .tabItem { Label(
  983. "Settings",
  984. systemImage: "gear"
  985. ) }.tag(3)
  986. }
  987. .tint(Color.tabBar)
  988. Button(
  989. action: {
  990. state.showModal(for: .bolus) },
  991. label: {
  992. Image(systemName: "plus.circle.fill")
  993. .font(.system(size: 40))
  994. .foregroundStyle(Color.tabBar)
  995. .padding(.bottom, 1)
  996. .padding(.horizontal, 22.5)
  997. }
  998. )
  999. }.ignoresSafeArea(.keyboard, edges: .bottom).blur(radius: state.waitForSuggestion ? 8 : 0)
  1000. .onChange(of: selectedTab) {
  1001. if !settingsPath.isEmpty {
  1002. settingsPath = NavigationPath()
  1003. }
  1004. }
  1005. }
  1006. var body: some View {
  1007. ZStack(alignment: .center) {
  1008. tabBar()
  1009. if state.waitForSuggestion {
  1010. CustomProgressView(text: String(localized: "Updating IOB...", comment: "Progress text when updating IOB"))
  1011. }
  1012. }
  1013. }
  1014. }
  1015. }
  1016. extension UIDevice {
  1017. public enum DeviceSize: CGFloat {
  1018. case smallDevice = 667 // Height for 4" iPhone SE
  1019. case largeDevice = 852 // Height for 6.1" iPhone 15 Pro
  1020. }
  1021. @usableFromInline static func adjustPadding(
  1022. min: CGFloat? = nil,
  1023. max: CGFloat? = nil
  1024. ) -> CGFloat? {
  1025. if UIScreen.screenHeight > UIDevice.DeviceSize.smallDevice.rawValue {
  1026. if UIScreen.screenHeight >= UIDevice.DeviceSize.largeDevice.rawValue {
  1027. return max
  1028. } else {
  1029. return min != nil ?
  1030. (max != nil ? max! * (UIScreen.screenHeight / UIDevice.DeviceSize.largeDevice.rawValue) : nil) : nil
  1031. }
  1032. } else {
  1033. return min
  1034. }
  1035. }
  1036. }
  1037. extension UIScreen {
  1038. static var screenHeight: CGFloat {
  1039. UIScreen.main.bounds.height
  1040. }
  1041. static var screenWidth: CGFloat {
  1042. UIScreen.main.bounds.width
  1043. }
  1044. }
  1045. /// Checks if the device is using a 24-hour time format.
  1046. func is24HourFormat() -> Bool {
  1047. let formatter = DateFormatter()
  1048. formatter.locale = Locale.current
  1049. formatter.dateStyle = .none
  1050. formatter.timeStyle = .short
  1051. let dateString = formatter.string(from: Date())
  1052. return !dateString.contains("AM") && !dateString.contains("PM")
  1053. }
  1054. /// Converts a duration in minutes to a formatted string (e.g., "1 hr 30 min").
  1055. func formatHrMin(_ durationInMinutes: Int) -> String {
  1056. let hours = durationInMinutes / 60
  1057. let minutes = durationInMinutes % 60
  1058. switch (hours, minutes) {
  1059. case let (0, m):
  1060. return "\(m) min"
  1061. case let (h, 0):
  1062. return "\(h) hr"
  1063. default:
  1064. return "\(hours) hr \(minutes) min"
  1065. }
  1066. }
  1067. // Helper function to convert a start and end hour to either 24-hour or AM/PM format
  1068. func formatTimeRange(start: String?, end: String?) -> String {
  1069. guard let start = start, let end = end else {
  1070. return ""
  1071. }
  1072. // Check if the format is 24-hour or AM/PM
  1073. if is24HourFormat() {
  1074. // Return the original 24-hour format
  1075. return "\(start)-\(end)"
  1076. } else {
  1077. // Convert to AM/PM format using DateFormatter
  1078. let formatter = DateFormatter()
  1079. formatter.dateFormat = "HH"
  1080. if let startHour = Int(start), let endHour = Int(end) {
  1081. let startDate = Calendar.current.date(bySettingHour: startHour, minute: 0, second: 0, of: Date()) ?? Date()
  1082. let endDate = Calendar.current.date(bySettingHour: endHour, minute: 0, second: 0, of: Date()) ?? Date()
  1083. // Customize the format to "2p" or "2a"
  1084. formatter.dateFormat = "ha"
  1085. let startFormatted = formatter.string(from: startDate).lowercased().replacingOccurrences(of: "m", with: "")
  1086. let endFormatted = formatter.string(from: endDate).lowercased().replacingOccurrences(of: "m", with: "")
  1087. return "\(startFormatted)-\(endFormatted)"
  1088. } else {
  1089. return ""
  1090. }
  1091. }
  1092. }