HomeRootView.swift 46 KB

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