HomeRootView.swift 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  1. import CoreData
  2. import SpriteKit
  3. import SwiftDate
  4. import SwiftUI
  5. import Swinject
  6. extension Home {
  7. struct RootView: BaseView {
  8. let resolver: Resolver
  9. @StateObject var state = StateModel()
  10. @State var isStatusPopupPresented = false
  11. @State var showCancelAlert = false
  12. @State var showTempTargetCancelAlert = false
  13. @State var isMenuPresented = false
  14. @State var showTreatments = false
  15. @State var selectedTab: Int = 0
  16. @State private var statusTitle: String = ""
  17. @State var showPumpSelection: Bool = false
  18. struct Buttons: Identifiable {
  19. let label: String
  20. let number: String
  21. var active: Bool
  22. let hours: Int16
  23. var id: String { label }
  24. }
  25. @State var timeButtons: [Buttons] = [
  26. Buttons(label: "2 hours", number: "2", active: false, hours: 2),
  27. Buttons(label: "4 hours", number: "4", active: false, hours: 4),
  28. Buttons(label: "6 hours", number: "6", active: false, hours: 6),
  29. Buttons(label: "12 hours", number: "12", active: false, hours: 12),
  30. Buttons(label: "24 hours", number: "24", active: false, hours: 24)
  31. ]
  32. let buttonFont = Font.custom("TimeButtonFont", size: 14)
  33. @Environment(\.managedObjectContext) var moc
  34. @Environment(\.colorScheme) var colorScheme
  35. @FetchRequest(fetchRequest: OverrideStored.fetch(
  36. NSPredicate.lastActiveOverride,
  37. ascending: false,
  38. fetchLimit: 1
  39. )) var latestOverride: FetchedResults<OverrideStored>
  40. @FetchRequest(fetchRequest: TempTargetStored.fetch(
  41. NSPredicate.lastActiveTempTarget,
  42. ascending: false,
  43. fetchLimit: 1
  44. )) var latestTempTarget: FetchedResults<TempTargetStored>
  45. var bolusProgressFormatter: NumberFormatter {
  46. let formatter = NumberFormatter()
  47. formatter.numberStyle = .decimal
  48. formatter.minimum = 0
  49. formatter.maximumFractionDigits = state.settingsManager.preferences.bolusIncrement > 0.05 ? 1 : 2
  50. formatter.minimumFractionDigits = state.settingsManager.preferences.bolusIncrement > 0.05 ? 1 : 2
  51. formatter.allowsFloats = true
  52. formatter.roundingIncrement = Double(state.settingsManager.preferences.bolusIncrement) as NSNumber
  53. return formatter
  54. }
  55. private var numberFormatter: NumberFormatter {
  56. let formatter = NumberFormatter()
  57. formatter.numberStyle = .decimal
  58. formatter.maximumFractionDigits = 2
  59. return formatter
  60. }
  61. private var fetchedTargetFormatter: NumberFormatter {
  62. let formatter = NumberFormatter()
  63. formatter.numberStyle = .decimal
  64. if state.units == .mmolL {
  65. formatter.maximumFractionDigits = 1
  66. } else { formatter.maximumFractionDigits = 0 }
  67. return formatter
  68. }
  69. private var targetFormatter: NumberFormatter {
  70. let formatter = NumberFormatter()
  71. formatter.numberStyle = .decimal
  72. formatter.maximumFractionDigits = 1
  73. return formatter
  74. }
  75. private var tirFormatter: NumberFormatter {
  76. let formatter = NumberFormatter()
  77. formatter.numberStyle = .decimal
  78. formatter.maximumFractionDigits = 0
  79. return formatter
  80. }
  81. private var dateFormatter: DateFormatter {
  82. let dateFormatter = DateFormatter()
  83. dateFormatter.timeStyle = .short
  84. return dateFormatter
  85. }
  86. private var color: LinearGradient {
  87. colorScheme == .dark ? LinearGradient(
  88. gradient: Gradient(colors: [
  89. Color.bgDarkBlue,
  90. Color.bgDarkerDarkBlue
  91. ]),
  92. startPoint: .top,
  93. endPoint: .bottom
  94. )
  95. :
  96. LinearGradient(
  97. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  98. startPoint: .top,
  99. endPoint: .bottom
  100. )
  101. }
  102. private var historySFSymbol: String {
  103. if #available(iOS 17.0, *) {
  104. return "book.pages"
  105. } else {
  106. return "book"
  107. }
  108. }
  109. var glucoseView: some View {
  110. CurrentGlucoseView(
  111. timerDate: $state.timerDate,
  112. units: $state.units,
  113. alarm: $state.alarm,
  114. lowGlucose: $state.lowGlucose,
  115. highGlucose: $state.highGlucose,
  116. cgmAvailable: $state.cgmAvailable,
  117. glucose: state.latestTwoGlucoseValues
  118. ).scaleEffect(0.9)
  119. .onTapGesture {
  120. state.openCGM()
  121. }
  122. .onLongPressGesture {
  123. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  124. impactHeavy.impactOccurred()
  125. state.showModal(for: .snooze)
  126. }
  127. }
  128. var pumpView: some View {
  129. PumpView(
  130. reservoir: $state.reservoir,
  131. name: $state.pumpName,
  132. expiresAtDate: $state.pumpExpiresAtDate,
  133. timerDate: $state.timerDate,
  134. timeZone: $state.timeZone,
  135. pumpStatusHighlightMessage: $state.pumpStatusHighlightMessage,
  136. battery: $state.batteryFromPersistence
  137. ).onTapGesture {
  138. if state.pumpDisplayState == nil {
  139. // shows user confirmation dialog with pump model choices, then proceeds to setup
  140. showPumpSelection.toggle()
  141. } else {
  142. // sends user to pump settings
  143. state.setupPump.toggle()
  144. }
  145. }
  146. }
  147. var tempBasalString: String? {
  148. guard let lastTempBasal = state.tempBasals.last?.tempBasal, let tempRate = lastTempBasal.rate else {
  149. return nil
  150. }
  151. let rateString = numberFormatter.string(from: tempRate as NSNumber) ?? "0"
  152. var manualBasalString = ""
  153. if let apsManager = state.apsManager, apsManager.isManualTempBasal {
  154. manualBasalString = NSLocalizedString(
  155. " - Manual Basal ⚠️",
  156. comment: "Manual Temp basal"
  157. )
  158. }
  159. return rateString + " " + NSLocalizedString(" U/hr", comment: "Unit per hour with space") + manualBasalString
  160. }
  161. var overrideString: String? {
  162. guard let latestOverride = latestOverride.first else {
  163. return nil
  164. }
  165. let percent = latestOverride.percentage
  166. let percentString = percent == 100 ? "" : "\(percent.formatted(.number)) %"
  167. let unit = state.units
  168. var target = (latestOverride.target ?? 100) as Decimal
  169. target = unit == .mmolL ? target.asMmolL : target
  170. var targetString = target == 0 ? "" : (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " + unit
  171. .rawValue
  172. if tempTargetString != nil {
  173. targetString = ""
  174. }
  175. let duration = latestOverride.duration ?? 0
  176. let addedMinutes = Int(truncating: duration)
  177. let date = latestOverride.date ?? Date()
  178. let newDuration = max(
  179. Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes),
  180. 0
  181. )
  182. let indefinite = latestOverride.indefinite
  183. var durationString = ""
  184. if !indefinite {
  185. if newDuration >= 1 {
  186. durationString =
  187. "\(newDuration.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) min"
  188. } else if newDuration > 0 {
  189. durationString =
  190. "\((newDuration * 60).formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) s"
  191. } else {
  192. /// Do not show the Override anymore
  193. Task {
  194. guard let objectID = self.latestOverride.first?.objectID else { return }
  195. await state.cancelOverride(withID: objectID)
  196. }
  197. }
  198. }
  199. let smbToggleString = latestOverride.smbIsOff ? " \u{20e0}" : ""
  200. let components = [percentString, targetString, durationString, smbToggleString].filter { !$0.isEmpty }
  201. return components.isEmpty ? nil : components.joined(separator: ", ")
  202. }
  203. var tempTargetString: String? {
  204. guard let latestTempTarget = latestTempTarget.first else {
  205. return nil
  206. }
  207. let name = latestTempTarget.name
  208. let duration = latestTempTarget.duration
  209. let addedMinutes = Int(truncating: duration ?? 0)
  210. let date = latestTempTarget.date ?? Date()
  211. let newDuration = max(
  212. Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes),
  213. 0
  214. )
  215. var durationString = ""
  216. let target = latestTempTarget.target
  217. var targetString = target == 0 ? "" : (fetchedTargetFormatter.string(from: (target ?? 0) as NSNumber) ?? "") + " " +
  218. state.units
  219. .rawValue
  220. if newDuration >= 1 {
  221. durationString =
  222. "\(newDuration.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) min"
  223. } else if newDuration > 0 {
  224. durationString =
  225. "\((newDuration * 60).formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) s"
  226. } else {
  227. /// Do not show the Override anymore
  228. Task {
  229. guard let objectID = self.latestTempTarget.first?.objectID else { return }
  230. await state.cancelOverride(withID: objectID)
  231. }
  232. }
  233. let components = [targetString, durationString].filter { !$0.isEmpty }
  234. return components.isEmpty ? nil : components.joined(separator: ", ")
  235. }
  236. var infoPanel: some View {
  237. HStack(alignment: .center) {
  238. if state.pumpSuspended {
  239. Text("Pump suspended")
  240. .font(.system(size: 15, weight: .bold)).foregroundColor(.loopGray)
  241. .padding(.leading, 8)
  242. } else if let tempBasalString = tempBasalString {
  243. Text(tempBasalString)
  244. .font(.system(size: 15, weight: .bold))
  245. .foregroundColor(.insulin)
  246. .padding(.leading, 8)
  247. }
  248. if state.totalInsulinDisplayType == .totalInsulinInScope {
  249. Text(
  250. "TINS: \(state.calculateTINS())" +
  251. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  252. )
  253. .font(.system(size: 15, weight: .bold))
  254. .foregroundColor(.insulin)
  255. }
  256. if let tempTargetString = tempTargetString {
  257. Text(tempTargetString)
  258. .font(.caption)
  259. .foregroundColor(.secondary)
  260. }
  261. Spacer()
  262. if state.closedLoop, state.settingsManager.preferences.maxIOB == 0 {
  263. Text("Max IOB: 0").font(.callout).foregroundColor(.orange).padding(.trailing, 20)
  264. }
  265. }
  266. .frame(maxWidth: .infinity, maxHeight: 30)
  267. }
  268. var timeInterval: some View {
  269. HStack(alignment: .center) {
  270. ForEach(timeButtons) { button in
  271. Text(button.active ? NSLocalizedString(button.label, comment: "") : button.number).onTapGesture {
  272. state.hours = button.hours
  273. }
  274. .foregroundStyle(button.active ? (colorScheme == .dark ? Color.white : Color.black).opacity(0.9) : .secondary)
  275. .frame(maxHeight: 30).padding(.horizontal, 8)
  276. .background(
  277. button.active ?
  278. // RGB(30, 60, 95)
  279. (
  280. colorScheme == .dark ? Color(red: 0.1176470588, green: 0.2352941176, blue: 0.3725490196) :
  281. Color.white
  282. ) :
  283. Color
  284. .clear
  285. )
  286. .cornerRadius(20)
  287. }
  288. Button(action: {
  289. state.isLegendPresented.toggle()
  290. }) {
  291. Image(systemName: "info")
  292. .foregroundColor(colorScheme == .dark ? Color.white : Color.black).opacity(0.9)
  293. .frame(width: 20, height: 20)
  294. .background(
  295. colorScheme == .dark ? Color(red: 0.1176470588, green: 0.2352941176, blue: 0.3725490196) :
  296. Color.white
  297. )
  298. .clipShape(Circle())
  299. }
  300. .padding([.top, .bottom])
  301. }
  302. .shadow(
  303. color: Color.black.opacity(colorScheme == .dark ? 0.75 : 0.33),
  304. radius: colorScheme == .dark ? 5 : 3
  305. )
  306. .font(buttonFont)
  307. }
  308. @ViewBuilder func mainChart(geo: GeometryProxy) -> some View {
  309. ZStack {
  310. MainChartView(
  311. geo: geo,
  312. units: $state.units,
  313. hours: .constant(state.filteredHours),
  314. tempTargets: $state.tempTargets,
  315. highGlucose: $state.highGlucose,
  316. lowGlucose: $state.lowGlucose,
  317. screenHours: $state.hours,
  318. displayXgridLines: $state.displayXgridLines,
  319. displayYgridLines: $state.displayYgridLines,
  320. thresholdLines: $state.thresholdLines,
  321. state: state
  322. )
  323. }
  324. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: nil))
  325. }
  326. func highlightButtons() {
  327. for i in 0 ..< timeButtons.count {
  328. timeButtons[i].active = timeButtons[i].hours == state.hours
  329. }
  330. }
  331. @ViewBuilder func rightHeaderPanel(_: GeometryProxy) -> some View {
  332. VStack(alignment: .leading, spacing: 20) {
  333. /// Loop view at bottomLeading
  334. LoopView(
  335. closedLoop: $state.closedLoop,
  336. timerDate: $state.timerDate,
  337. isLooping: $state.isLooping,
  338. lastLoopDate: $state.lastLoopDate,
  339. manualTempBasal: $state.manualTempBasal,
  340. determination: state.determinationsFromPersistence
  341. ).onTapGesture {
  342. state.isStatusPopupPresented = true
  343. setStatusTitle()
  344. }.onLongPressGesture {
  345. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  346. impactHeavy.impactOccurred()
  347. state.runLoop()
  348. }
  349. /// eventualBG string at bottomTrailing
  350. if let eventualBG = state.enactedAndNonEnactedDeterminations.first?.eventualBG {
  351. let bg = eventualBG as Decimal
  352. HStack {
  353. Image(systemName: "arrow.right.circle")
  354. .font(.system(size: 16, weight: .bold))
  355. Text(
  356. numberFormatter.string(
  357. from: (
  358. state.units == .mmolL ? bg
  359. .asMmolL : bg
  360. ) as NSNumber
  361. )!
  362. )
  363. .font(.system(size: 16))
  364. }
  365. } else {
  366. HStack {
  367. Image(systemName: "arrow.right.circle")
  368. .font(.system(size: 16, weight: .bold))
  369. Text("--")
  370. .font(.system(size: 16))
  371. }
  372. }
  373. }
  374. }
  375. @ViewBuilder func mealPanel(_: GeometryProxy) -> some View {
  376. HStack {
  377. HStack {
  378. Image(systemName: "syringe.fill")
  379. .font(.system(size: 16))
  380. .foregroundColor(Color.insulin)
  381. Text(
  382. (
  383. numberFormatter
  384. .string(from: (state.enactedAndNonEnactedDeterminations.first?.iob ?? 0) as NSNumber) ?? "0"
  385. ) +
  386. NSLocalizedString(" U", comment: "Insulin unit")
  387. )
  388. .font(.system(size: 16, weight: .bold, design: .rounded))
  389. }
  390. Spacer()
  391. HStack {
  392. Image(systemName: "fork.knife")
  393. .font(.system(size: 16))
  394. .foregroundColor(.loopYellow)
  395. Text(
  396. (
  397. numberFormatter
  398. .string(from: (state.enactedAndNonEnactedDeterminations.first?.cob ?? 0) as NSNumber) ?? "0"
  399. ) +
  400. NSLocalizedString(" g", comment: "gram of carbs")
  401. )
  402. .font(.system(size: 16, weight: .bold, design: .rounded))
  403. }
  404. Spacer()
  405. HStack {
  406. if state.pumpSuspended {
  407. Text("Pump suspended")
  408. .font(.system(size: 12, weight: .bold, design: .rounded)).foregroundColor(.loopGray)
  409. } else if let tempBasalString = tempBasalString {
  410. Image(systemName: "drop.circle")
  411. .font(.system(size: 16))
  412. .foregroundColor(.insulinTintColor)
  413. Text(tempBasalString)
  414. .font(.system(size: 16, weight: .bold, design: .rounded))
  415. } else {
  416. Image(systemName: "drop.circle")
  417. .font(.system(size: 16))
  418. .foregroundColor(.insulinTintColor)
  419. Text("No Data")
  420. .font(.system(size: 16, weight: .bold, design: .rounded))
  421. }
  422. }
  423. if state.totalInsulinDisplayType == .totalDailyDose {
  424. Spacer()
  425. Text(
  426. "TDD: " +
  427. (
  428. numberFormatter
  429. .string(from: (state.determinationsFromPersistence.first?.totalDailyDose ?? 0) as NSNumber) ??
  430. "0"
  431. ) +
  432. NSLocalizedString(" U", comment: "Insulin unit")
  433. )
  434. .font(.system(size: 16, weight: .bold, design: .rounded))
  435. } else {
  436. Spacer()
  437. HStack {
  438. Text(
  439. "TINS: \(state.roundedTotalBolus)" +
  440. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  441. )
  442. .font(.system(size: 16, weight: .bold, design: .rounded))
  443. .onChange(of: state.hours) { _ in
  444. state.roundedTotalBolus = state.calculateTINS()
  445. }
  446. .onAppear {
  447. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  448. state.roundedTotalBolus = state.calculateTINS()
  449. }
  450. }
  451. }
  452. }
  453. }.padding(.horizontal, 10)
  454. }
  455. @ViewBuilder func profileView(geo: GeometryProxy) -> some View {
  456. ZStack {
  457. // Background rectangle
  458. RoundedRectangle(cornerRadius: 15)
  459. .fill(
  460. colorScheme == .dark
  461. ? Color(red: 0.039, green: 0.133, blue: 0.216)
  462. : Color.insulin.opacity(0.1)
  463. )
  464. .frame(height: geo.size.height * 0.08)
  465. .shadow(
  466. color: colorScheme == .dark
  467. ? Color(red: 0.027, green: 0.11, blue: 0.141)
  468. : Color.black.opacity(0.33),
  469. radius: 3
  470. )
  471. HStack {
  472. if let overrideString = overrideString, let tempTargetString = tempTargetString {
  473. HStack {
  474. /// override section
  475. Image(systemName: "person.fill")
  476. .font(.system(size: 24))
  477. .foregroundStyle(Color.purple)
  478. VStack(alignment: .leading) {
  479. Text(latestOverride.first?.name ?? "Custom Override")
  480. .font(.subheadline)
  481. .frame(alignment: .leading)
  482. Text(overrideString)
  483. .font(.caption)
  484. }
  485. Spacer()
  486. Divider()
  487. .frame(height: geo.size.height * 0.05)
  488. .padding(.horizontal, 2)
  489. /// TempTarget section
  490. Image(systemName: "target")
  491. .font(.system(size: 24))
  492. .foregroundColor(.loopGreen)
  493. VStack(alignment: .leading) {
  494. Text(latestTempTarget.first?.name ?? "Temp Target")
  495. .font(.subheadline)
  496. Text(tempTargetString)
  497. .font(.caption)
  498. }
  499. Spacer()
  500. }
  501. } else
  502. if let overrideString = overrideString {
  503. // Only override is active
  504. HStack {
  505. Image(systemName: "person.fill")
  506. .font(.system(size: 24))
  507. .foregroundStyle(Color.purple)
  508. VStack(alignment: .leading) {
  509. Text(latestOverride.first?.name ?? "Custom Override")
  510. .font(.subheadline)
  511. Text(overrideString)
  512. .font(.caption)
  513. }
  514. Spacer()
  515. Image(systemName: "xmark")
  516. .font(.system(size: 25))
  517. .onTapGesture {
  518. if !latestOverride.isEmpty {
  519. showCancelAlert = true
  520. }
  521. }
  522. }
  523. } else
  524. if let tempTargetString = tempTargetString {
  525. // Only temp target is active
  526. HStack {
  527. Image(systemName: "target")
  528. .font(.system(size: 24))
  529. .foregroundColor(.loopGreen)
  530. VStack(alignment: .leading) {
  531. Text(latestTempTarget.first?.name ?? "Temp Target")
  532. .font(.subheadline)
  533. Text(tempTargetString)
  534. .font(.caption)
  535. }
  536. Spacer()
  537. Image(systemName: "xmark")
  538. .font(.system(size: 25))
  539. .onTapGesture {
  540. if !latestTempTarget.isEmpty {
  541. showTempTargetCancelAlert = true
  542. }
  543. }
  544. }
  545. } else {
  546. // Normal profile view
  547. VStack(alignment: .leading) {
  548. Text("Normal Profile")
  549. .font(.subheadline)
  550. Text("100 %")
  551. .font(.caption)
  552. }
  553. Spacer()
  554. // Placeholder xmark to keep layout consistent
  555. Image(systemName: "xmark")
  556. .font(.system(size: 25))
  557. .foregroundColor(.clear)
  558. }
  559. }
  560. .padding(5)
  561. }
  562. .padding(.horizontal, 10)
  563. .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  564. .alert(
  565. "Return to Normal?",
  566. isPresented: $showCancelAlert,
  567. actions: {
  568. Button("No", role: .cancel) {}
  569. Button("Yes", role: .destructive) {
  570. Task {
  571. if !latestOverride.isEmpty {
  572. guard let objectID = latestOverride.first?.objectID else { return }
  573. await state.cancelOverride(withID: objectID)
  574. }
  575. }
  576. }
  577. },
  578. message: { Text("This will change settings back to your normal profile.")
  579. }
  580. )
  581. .alert(
  582. "Cancel TempTarget?",
  583. isPresented: $showTempTargetCancelAlert,
  584. actions: {
  585. Button("No", role: .cancel) {}
  586. Button("Yes", role: .destructive) {
  587. Task {
  588. if !latestTempTarget.isEmpty {
  589. guard let objectID = latestTempTarget.first?.objectID else { return }
  590. await state.cancelTempTarget(withID: objectID)
  591. }
  592. }
  593. }
  594. },
  595. message: { Text("This will change settings back to your regular target.") }
  596. )
  597. }
  598. @ViewBuilder func bolusProgressBar(_ progress: Decimal) -> some View {
  599. GeometryReader { geo in
  600. RoundedRectangle(cornerRadius: 15)
  601. .frame(height: 6)
  602. .foregroundColor(.clear)
  603. .background(
  604. LinearGradient(colors: [
  605. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  606. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  607. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  608. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  609. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  610. ], startPoint: .leading, endPoint: .trailing)
  611. .mask(alignment: .leading) {
  612. RoundedRectangle(cornerRadius: 15)
  613. .frame(width: geo.size.width * CGFloat(progress))
  614. }
  615. )
  616. }
  617. }
  618. @ViewBuilder func bolusView(geo: GeometryProxy, _ progress: Decimal) -> some View {
  619. /// ensure that state.lastPumpBolus has a value, i.e. there is a last bolus done by the pump and not an external bolus
  620. /// - TRUE: show the pump bolus
  621. /// - FALSE: do not show a progress bar at all
  622. if let bolusTotal = state.lastPumpBolus?.bolus?.amount {
  623. let bolusFraction = progress * (bolusTotal as Decimal)
  624. let bolusString =
  625. (bolusProgressFormatter.string(from: bolusFraction as NSNumber) ?? "0")
  626. + " of " +
  627. (numberFormatter.string(from: bolusTotal as NSNumber) ?? "0")
  628. + NSLocalizedString(" U", comment: "Insulin unit")
  629. ZStack {
  630. /// rectangle as background
  631. RoundedRectangle(cornerRadius: 15)
  632. .fill(
  633. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color
  634. .insulin
  635. .opacity(0.2)
  636. )
  637. .clipShape(RoundedRectangle(cornerRadius: 15))
  638. .frame(height: geo.size.height * 0.08)
  639. .shadow(
  640. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  641. Color.black.opacity(0.33),
  642. radius: 3
  643. )
  644. /// actual bolus view
  645. HStack {
  646. Image(systemName: "cross.vial.fill")
  647. .font(.system(size: 25))
  648. Spacer()
  649. VStack {
  650. Text("Bolusing")
  651. .font(.subheadline)
  652. .frame(maxWidth: .infinity, alignment: .leading)
  653. Text(bolusString)
  654. .font(.caption)
  655. .frame(maxWidth: .infinity, alignment: .leading)
  656. }.padding(.leading, 5)
  657. Spacer()
  658. Button {
  659. state.showProgressView()
  660. state.cancelBolus()
  661. } label: {
  662. Image(systemName: "xmark.app")
  663. .font(.system(size: 25))
  664. }
  665. }.padding(.horizontal, 10)
  666. .padding(.trailing, 8)
  667. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  668. .overlay(alignment: .bottom) {
  669. bolusProgressBar(progress).padding(.horizontal, 18).offset(y: 48)
  670. }.clipShape(RoundedRectangle(cornerRadius: 15))
  671. }
  672. }
  673. @ViewBuilder func mainView() -> some View {
  674. GeometryReader { geo in
  675. VStack(spacing: 0) {
  676. ZStack {
  677. /// glucose bobble
  678. glucoseView
  679. /// right panel with loop status and evBG
  680. HStack {
  681. Spacer()
  682. rightHeaderPanel(geo)
  683. }.padding(.trailing, 20)
  684. /// left panel with pump related info
  685. HStack {
  686. pumpView
  687. Spacer()
  688. }.padding(.leading, 20)
  689. }.padding(.top, 10)
  690. mealPanel(geo).padding(.top, UIDevice.adjustPadding(min: nil, max: 30))
  691. .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 20))
  692. mainChart(geo: geo)
  693. timeInterval.padding(.top, UIDevice.adjustPadding(min: 0, max: 12))
  694. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: 12))
  695. if let progress = state.bolusProgress {
  696. bolusView(geo: geo, progress).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  697. } else {
  698. if overrideString != nil || tempTargetString != nil { // kills the Normal Profile View
  699. profileView(geo: geo).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  700. }
  701. }
  702. }
  703. .background(color)
  704. }
  705. .onChange(of: state.hours) { _ in
  706. highlightButtons()
  707. }
  708. .onAppear {
  709. configureView {
  710. highlightButtons()
  711. }
  712. }
  713. .navigationTitle("Home")
  714. .navigationBarHidden(true)
  715. .ignoresSafeArea(.keyboard)
  716. .popup(isPresented: state.isStatusPopupPresented, alignment: .top, direction: .top) {
  717. popup
  718. .padding()
  719. .background(
  720. RoundedRectangle(cornerRadius: 8, style: .continuous)
  721. .fill(colorScheme == .dark ? Color(
  722. "Chart"
  723. ) : Color(UIColor.darkGray))
  724. )
  725. .onTapGesture {
  726. state.isStatusPopupPresented = false
  727. }
  728. .gesture(
  729. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  730. .onEnded { value in
  731. if value.translation.height < 0 {
  732. state.isStatusPopupPresented = false
  733. }
  734. }
  735. )
  736. }
  737. .confirmationDialog("Pump Model", isPresented: $showPumpSelection) {
  738. Button("Medtronic") { state.addPump(.minimed) }
  739. Button("Omnipod Eros") { state.addPump(.omnipod) }
  740. Button("Omnipod Dash") { state.addPump(.omnipodBLE) }
  741. Button("Pump Simulator") { state.addPump(.simulator) }
  742. } message: { Text("Select Pump Model") }
  743. .sheet(isPresented: $state.setupPump) {
  744. if let pumpManager = state.provider.apsManager.pumpManager {
  745. PumpConfig.PumpSettingsView(
  746. pumpManager: pumpManager,
  747. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  748. completionDelegate: state,
  749. setupDelegate: state
  750. )
  751. } else {
  752. PumpConfig.PumpSetupView(
  753. pumpType: state.setupPumpType,
  754. pumpInitialSettings: PumpConfig.PumpInitialSettings.default,
  755. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  756. completionDelegate: state,
  757. setupDelegate: state
  758. )
  759. }
  760. }
  761. .sheet(isPresented: $state.isLegendPresented) {
  762. NavigationStack {
  763. Text(
  764. "The oref algorithm determines insulin dosing based on a number of scenarios that it estimates with different types of forecasts."
  765. )
  766. .font(.subheadline)
  767. .foregroundColor(.secondary)
  768. if state.forecastDisplayType == .lines {
  769. List {
  770. DefinitionRow(
  771. term: "IOB (Insulin on Board)",
  772. definition: "Forecasts BG based on the amount of insulin still active in the body.",
  773. color: .insulin
  774. )
  775. DefinitionRow(
  776. term: "ZT (Zero-Temp)",
  777. definition: "Forecasts the worst-case blood glucose (BG) scenario if no carbs are absorbed and insulin delivery is stopped until BG starts rising.",
  778. color: .zt
  779. )
  780. DefinitionRow(
  781. term: "COB (Carbs on Board)",
  782. definition: "Forecasts BG changes by considering the amount of carbohydrates still being absorbed in the body.",
  783. color: .loopYellow
  784. )
  785. DefinitionRow(
  786. term: "UAM (Unannounced Meal)",
  787. definition: "Forecasts BG levels and insulin dosing needs for unexpected meals or other causes of BG rises without prior notice.",
  788. color: .uam
  789. )
  790. }
  791. .padding(.trailing, 10)
  792. .navigationBarTitle("Legend", displayMode: .inline)
  793. } else {
  794. List {
  795. DefinitionRow(
  796. term: "Cone of Uncertainty",
  797. definition: "For simplicity reasons, oref's various forecast curves are displayed as a \"Cone of Uncertainty\" that depicts a possible, forecasted range of future glucose fluctuation based on the current data and the algothim's result.\n\nTo modify the forecast display type, go to Trio Settings > Features > User Interface > Forecast Display Type.",
  798. color: Color.blue.opacity(0.5)
  799. )
  800. }
  801. .padding(.trailing, 10)
  802. .navigationBarTitle("Legend", displayMode: .inline)
  803. }
  804. Button { state.isLegendPresented.toggle() }
  805. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  806. .buttonStyle(.bordered)
  807. .padding(.top)
  808. }
  809. .padding()
  810. .presentationDetents(
  811. [.fraction(0.9), .large],
  812. selection: $state.legendSheetDetent
  813. )
  814. }
  815. }
  816. @State var settingsPath = NavigationPath()
  817. @ViewBuilder func tabBar() -> some View {
  818. ZStack(alignment: .bottom) {
  819. TabView(selection: $selectedTab) {
  820. let carbsRequiredBadge: String? = {
  821. guard let carbsRequired = state.enactedAndNonEnactedDeterminations.first?.carbsRequired,
  822. state.showCarbsRequiredBadge
  823. else {
  824. return nil
  825. }
  826. let carbsRequiredDecimal = Decimal(carbsRequired)
  827. if carbsRequiredDecimal > state.settingsManager.settings.carbsRequiredThreshold {
  828. let numberAsNSNumber = NSDecimalNumber(decimal: carbsRequiredDecimal)
  829. return (numberFormatter.string(from: numberAsNSNumber) ?? "") + " g"
  830. }
  831. return nil
  832. }()
  833. NavigationStack { mainView() }
  834. .tabItem { Label("Main", systemImage: "chart.xyaxis.line") }
  835. .badge(carbsRequiredBadge).tag(0)
  836. NavigationStack { DataTable.RootView(resolver: resolver) }
  837. .tabItem { Label("History", systemImage: historySFSymbol) }.tag(1)
  838. Spacer()
  839. NavigationStack { OverrideConfig.RootView(resolver: resolver) }
  840. .tabItem {
  841. Label(
  842. "Adjustments",
  843. systemImage: "slider.horizontal.2.gobackward"
  844. ) }.tag(2)
  845. NavigationStack(path: self.$settingsPath) {
  846. Settings.RootView(resolver: resolver) }
  847. .tabItem { Label(
  848. "Settings",
  849. systemImage: "gear"
  850. ) }.tag(3)
  851. }
  852. .tint(Color.tabBar)
  853. Button(
  854. action: {
  855. state.showModal(for: .bolus) },
  856. label: {
  857. Image(systemName: "plus.circle.fill")
  858. .font(.system(size: 40))
  859. .foregroundStyle(Color.tabBar)
  860. .padding(.bottom, 1)
  861. .padding(.horizontal, 20)
  862. }
  863. )
  864. }.ignoresSafeArea(.keyboard, edges: .bottom).blur(radius: state.waitForSuggestion ? 8 : 0)
  865. .onChange(of: selectedTab) { _ in
  866. print("current path is empty: \(settingsPath.isEmpty)")
  867. settingsPath = NavigationPath()
  868. }
  869. }
  870. var body: some View {
  871. ZStack(alignment: .center) {
  872. tabBar()
  873. if state.waitForSuggestion {
  874. CustomProgressView(text: "Updating IOB...")
  875. }
  876. }
  877. }
  878. private func parseReasonConclusion(_ reasonConclusion: String, isMmolL: Bool) -> String {
  879. var updatedConclusion = reasonConclusion
  880. // Handle "minGuardBG x<y" pattern
  881. if let range = updatedConclusion.range(of: "minGuardBG\\s*-?\\d+<\\d+", options: .regularExpression) {
  882. let matchedString = updatedConclusion[range]
  883. let parts = matchedString.components(separatedBy: "<")
  884. if let firstValue = Double(parts[0].components(separatedBy: CharacterSet.decimalDigits.inverted).joined()),
  885. let secondValue = Double(parts[1])
  886. {
  887. let formattedFirstValue = isMmolL ? Double(firstValue.asMmolL) : firstValue
  888. let formattedSecondValue = isMmolL ? Double(secondValue.asMmolL) : secondValue
  889. let formattedString = "minGuardBG \(formattedFirstValue)<\(formattedSecondValue)"
  890. updatedConclusion = updatedConclusion.replacingOccurrences(of: matchedString, with: formattedString)
  891. }
  892. }
  893. // Handle "Eventual BG x >= target" pattern
  894. if let range = updatedConclusion.range(of: "Eventual BG\\s*\\d+\\s*>?=\\s*\\d+", options: .regularExpression) {
  895. let matchedString = updatedConclusion[range]
  896. let parts = matchedString.components(separatedBy: " >= ")
  897. if let firstValue = Double(parts[0].components(separatedBy: CharacterSet.decimalDigits.inverted).joined()),
  898. let secondValue = Double(parts[1])
  899. {
  900. let formattedFirstValue = isMmolL ? Double(firstValue.asMmolL) : firstValue
  901. let formattedSecondValue = isMmolL ? Double(secondValue.asMmolL) : secondValue
  902. let formattedString = "Eventual BG \(formattedFirstValue) >= \(formattedSecondValue)"
  903. updatedConclusion = updatedConclusion.replacingOccurrences(of: matchedString, with: formattedString)
  904. }
  905. }
  906. return updatedConclusion.capitalizingFirstLetter()
  907. }
  908. private var popup: some View {
  909. VStack(alignment: .leading, spacing: 4) {
  910. Text(statusTitle).font(.headline).foregroundColor(.white)
  911. .padding(.bottom, 4)
  912. if let determination = state.determinationsFromPersistence.first {
  913. if determination.glucose == 400 {
  914. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  915. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  916. } else {
  917. let tags = !state.isSmoothingEnabled ? determination.reasonParts : determination
  918. .reasonParts + ["Smoothing: On"]
  919. TagCloudView(
  920. tags: tags,
  921. shouldParseToMmolL: state.units == .mmolL
  922. )
  923. .animation(.none, value: false)
  924. Text(
  925. self
  926. .parseReasonConclusion(
  927. determination.reasonConclusion,
  928. isMmolL: state.units == .mmolL
  929. )
  930. ).font(.caption).foregroundColor(.white)
  931. }
  932. } else {
  933. Text("No determination found").font(.body).foregroundColor(.white)
  934. }
  935. if let errorMessage = state.errorMessage, let date = state.errorDate {
  936. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  937. .foregroundColor(.white)
  938. .font(.headline)
  939. .padding(.bottom, 4)
  940. .padding(.top, 8)
  941. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  942. }
  943. }
  944. }
  945. private func setStatusTitle() {
  946. if let determination = state.determinationsFromPersistence.first {
  947. let dateFormatter = DateFormatter()
  948. dateFormatter.timeStyle = .short
  949. statusTitle = NSLocalizedString("Oref Determination enacted at", comment: "Headline in enacted pop up") +
  950. " " +
  951. dateFormatter
  952. .string(from: determination.deliverAt ?? Date())
  953. } else {
  954. statusTitle = "No Oref determination"
  955. return
  956. }
  957. }
  958. }
  959. }
  960. extension UIDevice {
  961. public enum DeviceSize: CGFloat {
  962. case smallDevice = 667 // Height for 4" iPhone SE
  963. case largeDevice = 852 // Height for 6.1" iPhone 15 Pro
  964. }
  965. @usableFromInline static func adjustPadding(min: CGFloat? = nil, max: CGFloat? = nil) -> CGFloat? {
  966. if UIScreen.screenHeight > UIDevice.DeviceSize.smallDevice.rawValue {
  967. if UIScreen.screenHeight >= UIDevice.DeviceSize.largeDevice.rawValue {
  968. return max
  969. } else {
  970. return min != nil ?
  971. (max != nil ? max! * (UIScreen.screenHeight / UIDevice.DeviceSize.largeDevice.rawValue) : nil) : nil
  972. }
  973. } else {
  974. return min
  975. }
  976. }
  977. }
  978. extension UIScreen {
  979. static var screenHeight: CGFloat {
  980. UIScreen.main.bounds.height
  981. }
  982. static var screenWidth: CGFloat {
  983. UIScreen.main.bounds.width
  984. }
  985. }