HomeRootView.swift 52 KB

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