HomeRootView.swift 46 KB

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