HomeRootView.swift 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  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(spacing: 15) {
  472. // Profile icon
  473. Image(systemName: "person.fill")
  474. .font(.system(size: 25))
  475. Spacer()
  476. if let overrideString = overrideString, let tempTargetString = tempTargetString {
  477. // Both override and temp target are active
  478. HStack(spacing: 15) {
  479. // Override section
  480. HStack {
  481. VStack(alignment: .leading) {
  482. Text(latestOverride.first?.name ?? "Custom Override")
  483. .font(.subheadline)
  484. Text("\(overrideString)")
  485. .font(.caption)
  486. }
  487. .onTapGesture {
  488. if !latestOverride.isEmpty {
  489. showCancelAlert = true
  490. }
  491. }
  492. Image(systemName: "xmark")
  493. .font(.system(size: 25))
  494. .onTapGesture {
  495. if !latestOverride.isEmpty {
  496. showCancelAlert = true
  497. }
  498. }
  499. }
  500. Divider()
  501. .frame(height: geo.size.height * 0.05)
  502. .padding(.horizontal, 5)
  503. // Temp Target section
  504. HStack {
  505. VStack(alignment: .leading) {
  506. Text(latestTempTarget.first?.name ?? "Temp Target")
  507. .font(.subheadline)
  508. Text("\(tempTargetString)")
  509. .font(.caption)
  510. }
  511. .onTapGesture {
  512. if !latestTempTarget.isEmpty {
  513. showTempTargetCancelAlert = true
  514. }
  515. }
  516. Image(systemName: "xmark")
  517. .font(.system(size: 25))
  518. .onTapGesture {
  519. if !latestTempTarget.isEmpty {
  520. showTempTargetCancelAlert = true
  521. }
  522. }
  523. }
  524. }
  525. } else if let overrideString = overrideString {
  526. // Only override is active
  527. HStack {
  528. VStack(alignment: .leading) {
  529. Text(latestOverride.first?.name ?? "Custom Override")
  530. .font(.subheadline)
  531. Text("\(overrideString)")
  532. .font(.caption)
  533. }
  534. .onTapGesture {
  535. if !latestOverride.isEmpty {
  536. showCancelAlert = true
  537. }
  538. }
  539. Spacer()
  540. Image(systemName: "xmark")
  541. .font(.system(size: 25))
  542. .onTapGesture {
  543. if !latestOverride.isEmpty {
  544. showCancelAlert = true
  545. }
  546. }
  547. }
  548. } else if let tempTargetString = tempTargetString {
  549. // Only temp target is active
  550. HStack {
  551. VStack(alignment: .leading) {
  552. Text(latestTempTarget.first?.name ?? "Temp Target")
  553. .font(.subheadline)
  554. Text("\(tempTargetString)")
  555. .font(.caption)
  556. }
  557. .onTapGesture {
  558. if !latestTempTarget.isEmpty {
  559. showTempTargetCancelAlert = true
  560. }
  561. }
  562. Spacer()
  563. Image(systemName: "xmark")
  564. .font(.system(size: 25))
  565. .onTapGesture {
  566. if !latestTempTarget.isEmpty {
  567. showTempTargetCancelAlert = true
  568. }
  569. }
  570. }
  571. } else {
  572. // Normal profile view
  573. VStack(alignment: .leading) {
  574. Text("Normal Profile")
  575. .font(.subheadline)
  576. Text("100 %")
  577. .font(.caption)
  578. }
  579. Spacer()
  580. // Placeholder xmark to keep layout consistent
  581. Image(systemName: "xmark")
  582. .font(.system(size: 25))
  583. .foregroundColor(.clear)
  584. }
  585. }
  586. .padding(.horizontal, 10)
  587. }
  588. .padding(.horizontal, 10)
  589. .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  590. .alert(
  591. "Return to Normal?",
  592. isPresented: $showCancelAlert,
  593. actions: {
  594. Button("No", role: .cancel) {}
  595. Button("Yes", role: .destructive) {
  596. Task {
  597. if !latestOverride.isEmpty {
  598. guard let objectID = latestOverride.first?.objectID else { return }
  599. await state.cancelOverride(withID: objectID)
  600. }
  601. }
  602. }
  603. },
  604. message: { Text("This will change settings back to your normal profile.") }
  605. )
  606. .alert(
  607. "Return to Normal?",
  608. isPresented: $showTempTargetCancelAlert,
  609. actions: {
  610. Button("No", role: .cancel) {}
  611. Button("Yes", role: .destructive) {
  612. Task {
  613. if !latestTempTarget.isEmpty {
  614. guard let objectID = latestTempTarget.first?.objectID else { return }
  615. await state.cancelTempTarget(withID: objectID)
  616. }
  617. }
  618. }
  619. },
  620. message: { Text("This will change settings back to your normal profile.") }
  621. )
  622. }
  623. @ViewBuilder func bolusProgressBar(_ progress: Decimal) -> some View {
  624. GeometryReader { geo in
  625. RoundedRectangle(cornerRadius: 15)
  626. .frame(height: 6)
  627. .foregroundColor(.clear)
  628. .background(
  629. LinearGradient(colors: [
  630. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  631. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  632. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  633. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  634. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  635. ], startPoint: .leading, endPoint: .trailing)
  636. .mask(alignment: .leading) {
  637. RoundedRectangle(cornerRadius: 15)
  638. .frame(width: geo.size.width * CGFloat(progress))
  639. }
  640. )
  641. }
  642. }
  643. @ViewBuilder func bolusView(geo: GeometryProxy, _ progress: Decimal) -> some View {
  644. /// ensure that state.lastPumpBolus has a value, i.e. there is a last bolus done by the pump and not an external bolus
  645. /// - TRUE: show the pump bolus
  646. /// - FALSE: do not show a progress bar at all
  647. if let bolusTotal = state.lastPumpBolus?.bolus?.amount {
  648. let bolusFraction = progress * (bolusTotal as Decimal)
  649. let bolusString =
  650. (bolusProgressFormatter.string(from: bolusFraction as NSNumber) ?? "0")
  651. + " of " +
  652. (numberFormatter.string(from: bolusTotal as NSNumber) ?? "0")
  653. + NSLocalizedString(" U", comment: "Insulin unit")
  654. ZStack {
  655. /// rectangle as background
  656. RoundedRectangle(cornerRadius: 15)
  657. .fill(
  658. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color
  659. .insulin
  660. .opacity(0.2)
  661. )
  662. .clipShape(RoundedRectangle(cornerRadius: 15))
  663. .frame(height: geo.size.height * 0.08)
  664. .shadow(
  665. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  666. Color.black.opacity(0.33),
  667. radius: 3
  668. )
  669. /// actual bolus view
  670. HStack {
  671. Image(systemName: "cross.vial.fill")
  672. .font(.system(size: 25))
  673. Spacer()
  674. VStack {
  675. Text("Bolusing")
  676. .font(.subheadline)
  677. .frame(maxWidth: .infinity, alignment: .leading)
  678. Text(bolusString)
  679. .font(.caption)
  680. .frame(maxWidth: .infinity, alignment: .leading)
  681. }.padding(.leading, 5)
  682. Spacer()
  683. Button {
  684. state.showProgressView()
  685. state.cancelBolus()
  686. } label: {
  687. Image(systemName: "xmark.app")
  688. .font(.system(size: 25))
  689. }
  690. }.padding(.horizontal, 10)
  691. .padding(.trailing, 8)
  692. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  693. .overlay(alignment: .bottom) {
  694. bolusProgressBar(progress).padding(.horizontal, 18).offset(y: 48)
  695. }.clipShape(RoundedRectangle(cornerRadius: 15))
  696. }
  697. }
  698. @ViewBuilder func mainView() -> some View {
  699. GeometryReader { geo in
  700. VStack(spacing: 0) {
  701. ZStack {
  702. /// glucose bobble
  703. glucoseView
  704. /// right panel with loop status and evBG
  705. HStack {
  706. Spacer()
  707. rightHeaderPanel(geo)
  708. }.padding(.trailing, 20)
  709. /// left panel with pump related info
  710. HStack {
  711. pumpView
  712. Spacer()
  713. }.padding(.leading, 20)
  714. }.padding(.top, 10)
  715. mealPanel(geo).padding(.top, UIDevice.adjustPadding(min: nil, max: 30))
  716. .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 20))
  717. mainChart(geo: geo)
  718. timeInterval.padding(.top, UIDevice.adjustPadding(min: 0, max: 12))
  719. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: 12))
  720. if let progress = state.bolusProgress {
  721. bolusView(geo: geo, progress).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  722. } else {
  723. profileView(geo: geo).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  724. }
  725. }
  726. .background(color)
  727. }
  728. .onChange(of: state.hours) { _ in
  729. highlightButtons()
  730. }
  731. .onAppear {
  732. configureView {
  733. highlightButtons()
  734. }
  735. }
  736. .navigationTitle("Home")
  737. .navigationBarHidden(true)
  738. .ignoresSafeArea(.keyboard)
  739. .popup(isPresented: state.isStatusPopupPresented, alignment: .top, direction: .top) {
  740. popup
  741. .padding()
  742. .background(
  743. RoundedRectangle(cornerRadius: 8, style: .continuous)
  744. .fill(colorScheme == .dark ? Color(
  745. "Chart"
  746. ) : Color(UIColor.darkGray))
  747. )
  748. .onTapGesture {
  749. state.isStatusPopupPresented = false
  750. }
  751. .gesture(
  752. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  753. .onEnded { value in
  754. if value.translation.height < 0 {
  755. state.isStatusPopupPresented = false
  756. }
  757. }
  758. )
  759. }
  760. .confirmationDialog("Pump Model", isPresented: $showPumpSelection) {
  761. Button("Medtronic") { state.addPump(.minimed) }
  762. Button("Omnipod Eros") { state.addPump(.omnipod) }
  763. Button("Omnipod Dash") { state.addPump(.omnipodBLE) }
  764. Button("Pump Simulator") { state.addPump(.simulator) }
  765. } message: { Text("Select Pump Model") }
  766. .sheet(isPresented: $state.setupPump) {
  767. if let pumpManager = state.provider.apsManager.pumpManager {
  768. PumpConfig.PumpSettingsView(
  769. pumpManager: pumpManager,
  770. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  771. completionDelegate: state,
  772. setupDelegate: state
  773. )
  774. } else {
  775. PumpConfig.PumpSetupView(
  776. pumpType: state.setupPumpType,
  777. pumpInitialSettings: PumpConfig.PumpInitialSettings.default,
  778. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  779. completionDelegate: state,
  780. setupDelegate: state
  781. )
  782. }
  783. }
  784. .sheet(isPresented: $state.isLegendPresented) {
  785. NavigationStack {
  786. Text(
  787. "The oref algorithm determines insulin dosing based on a number of scenarios that it estimates with different types of forecasts."
  788. )
  789. .font(.subheadline)
  790. .foregroundColor(.secondary)
  791. if state.forecastDisplayType == .lines {
  792. List {
  793. DefinitionRow(
  794. term: "IOB (Insulin on Board)",
  795. definition: "Forecasts BG based on the amount of insulin still active in the body.",
  796. color: .insulin
  797. )
  798. DefinitionRow(
  799. term: "ZT (Zero-Temp)",
  800. definition: "Forecasts the worst-case blood glucose (BG) scenario if no carbs are absorbed and insulin delivery is stopped until BG starts rising.",
  801. color: .zt
  802. )
  803. DefinitionRow(
  804. term: "COB (Carbs on Board)",
  805. definition: "Forecasts BG changes by considering the amount of carbohydrates still being absorbed in the body.",
  806. color: .loopYellow
  807. )
  808. DefinitionRow(
  809. term: "UAM (Unannounced Meal)",
  810. definition: "Forecasts BG levels and insulin dosing needs for unexpected meals or other causes of BG rises without prior notice.",
  811. color: .uam
  812. )
  813. }
  814. .padding(.trailing, 10)
  815. .navigationBarTitle("Legend", displayMode: .inline)
  816. } else {
  817. List {
  818. DefinitionRow(
  819. term: "Cone of Uncertainty",
  820. 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.",
  821. color: Color.blue.opacity(0.5)
  822. )
  823. }
  824. .padding(.trailing, 10)
  825. .navigationBarTitle("Legend", displayMode: .inline)
  826. }
  827. Button { state.isLegendPresented.toggle() }
  828. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  829. .buttonStyle(.bordered)
  830. .padding(.top)
  831. }
  832. .padding()
  833. .presentationDetents(
  834. [.fraction(0.9), .large],
  835. selection: $state.legendSheetDetent
  836. )
  837. }
  838. }
  839. @State var settingsPath = NavigationPath()
  840. @ViewBuilder func tabBar() -> some View {
  841. ZStack(alignment: .bottom) {
  842. TabView(selection: $selectedTab) {
  843. let carbsRequiredBadge: String? = {
  844. guard let carbsRequired = state.enactedAndNonEnactedDeterminations.first?.carbsRequired,
  845. state.showCarbsRequiredBadge
  846. else {
  847. return nil
  848. }
  849. let carbsRequiredDecimal = Decimal(carbsRequired)
  850. if carbsRequiredDecimal > state.settingsManager.settings.carbsRequiredThreshold {
  851. let numberAsNSNumber = NSDecimalNumber(decimal: carbsRequiredDecimal)
  852. return (numberFormatter.string(from: numberAsNSNumber) ?? "") + " g"
  853. }
  854. return nil
  855. }()
  856. NavigationStack { mainView() }
  857. .tabItem { Label("Main", systemImage: "chart.xyaxis.line") }
  858. .badge(carbsRequiredBadge).tag(0)
  859. NavigationStack { DataTable.RootView(resolver: resolver) }
  860. .tabItem { Label("History", systemImage: historySFSymbol) }.tag(1)
  861. Spacer()
  862. NavigationStack { OverrideConfig.RootView(resolver: resolver) }
  863. .tabItem {
  864. Label(
  865. "Adjustments",
  866. systemImage: "slider.horizontal.2.gobackward"
  867. ) }.tag(2)
  868. NavigationStack(path: self.$settingsPath) {
  869. Settings.RootView(resolver: resolver) }
  870. .tabItem { Label(
  871. "Settings",
  872. systemImage: "gear"
  873. ) }.tag(3)
  874. }
  875. .tint(Color.tabBar)
  876. Button(
  877. action: {
  878. state.showModal(for: .bolus) },
  879. label: {
  880. Image(systemName: "plus.circle.fill")
  881. .font(.system(size: 40))
  882. .foregroundStyle(Color.tabBar)
  883. .padding(.bottom, 1)
  884. .padding(.horizontal, 20)
  885. }
  886. )
  887. }.ignoresSafeArea(.keyboard, edges: .bottom).blur(radius: state.waitForSuggestion ? 8 : 0)
  888. .onChange(of: selectedTab) { _ in
  889. print("current path is empty: \(settingsPath.isEmpty)")
  890. settingsPath = NavigationPath()
  891. }
  892. }
  893. var body: some View {
  894. ZStack(alignment: .center) {
  895. tabBar()
  896. if state.waitForSuggestion {
  897. CustomProgressView(text: "Updating IOB...")
  898. }
  899. }
  900. }
  901. private func parseReasonConclusion(_ reasonConclusion: String, isMmolL: Bool) -> String {
  902. var updatedConclusion = reasonConclusion
  903. // Handle "minGuardBG x<y" pattern
  904. if let range = updatedConclusion.range(of: "minGuardBG\\s*-?\\d+<\\d+", options: .regularExpression) {
  905. let matchedString = updatedConclusion[range]
  906. let parts = matchedString.components(separatedBy: "<")
  907. if let firstValue = Double(parts[0].components(separatedBy: CharacterSet.decimalDigits.inverted).joined()),
  908. let secondValue = Double(parts[1])
  909. {
  910. let formattedFirstValue = isMmolL ? Double(firstValue.asMmolL) : firstValue
  911. let formattedSecondValue = isMmolL ? Double(secondValue.asMmolL) : secondValue
  912. let formattedString = "minGuardBG \(formattedFirstValue)<\(formattedSecondValue)"
  913. updatedConclusion = updatedConclusion.replacingOccurrences(of: matchedString, with: formattedString)
  914. }
  915. }
  916. // Handle "Eventual BG x >= target" pattern
  917. if let range = updatedConclusion.range(of: "Eventual BG\\s*\\d+\\s*>?=\\s*\\d+", options: .regularExpression) {
  918. let matchedString = updatedConclusion[range]
  919. let parts = matchedString.components(separatedBy: " >= ")
  920. if let firstValue = Double(parts[0].components(separatedBy: CharacterSet.decimalDigits.inverted).joined()),
  921. let secondValue = Double(parts[1])
  922. {
  923. let formattedFirstValue = isMmolL ? Double(firstValue.asMmolL) : firstValue
  924. let formattedSecondValue = isMmolL ? Double(secondValue.asMmolL) : secondValue
  925. let formattedString = "Eventual BG \(formattedFirstValue) >= \(formattedSecondValue)"
  926. updatedConclusion = updatedConclusion.replacingOccurrences(of: matchedString, with: formattedString)
  927. }
  928. }
  929. return updatedConclusion.capitalizingFirstLetter()
  930. }
  931. private var popup: some View {
  932. VStack(alignment: .leading, spacing: 4) {
  933. Text(statusTitle).font(.headline).foregroundColor(.white)
  934. .padding(.bottom, 4)
  935. if let determination = state.determinationsFromPersistence.first {
  936. if determination.glucose == 400 {
  937. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  938. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  939. } else {
  940. let tags = !state.isSmoothingEnabled ? determination.reasonParts : determination
  941. .reasonParts + ["Smoothing: On"]
  942. TagCloudView(
  943. tags: tags,
  944. shouldParseToMmolL: state.units == .mmolL
  945. )
  946. .animation(.none, value: false)
  947. Text(
  948. self
  949. .parseReasonConclusion(
  950. determination.reasonConclusion,
  951. isMmolL: state.units == .mmolL
  952. )
  953. ).font(.caption).foregroundColor(.white)
  954. }
  955. } else {
  956. Text("No determination found").font(.body).foregroundColor(.white)
  957. }
  958. if let errorMessage = state.errorMessage, let date = state.errorDate {
  959. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  960. .foregroundColor(.white)
  961. .font(.headline)
  962. .padding(.bottom, 4)
  963. .padding(.top, 8)
  964. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  965. }
  966. }
  967. }
  968. private func setStatusTitle() {
  969. if let determination = state.determinationsFromPersistence.first {
  970. let dateFormatter = DateFormatter()
  971. dateFormatter.timeStyle = .short
  972. statusTitle = NSLocalizedString("Oref Determination enacted at", comment: "Headline in enacted pop up") +
  973. " " +
  974. dateFormatter
  975. .string(from: determination.deliverAt ?? Date())
  976. } else {
  977. statusTitle = "No Oref determination"
  978. return
  979. }
  980. }
  981. }
  982. }
  983. extension UIDevice {
  984. public enum DeviceSize: CGFloat {
  985. case smallDevice = 667 // Height for 4" iPhone SE
  986. case largeDevice = 852 // Height for 6.1" iPhone 15 Pro
  987. }
  988. @usableFromInline static func adjustPadding(min: CGFloat? = nil, max: CGFloat? = nil) -> CGFloat? {
  989. if UIScreen.screenHeight > UIDevice.DeviceSize.smallDevice.rawValue {
  990. if UIScreen.screenHeight >= UIDevice.DeviceSize.largeDevice.rawValue {
  991. return max
  992. } else {
  993. return min != nil ?
  994. (max != nil ? max! * (UIScreen.screenHeight / UIDevice.DeviceSize.largeDevice.rawValue) : nil) : nil
  995. }
  996. } else {
  997. return min
  998. }
  999. }
  1000. }
  1001. extension UIScreen {
  1002. static var screenHeight: CGFloat {
  1003. UIScreen.main.bounds.height
  1004. }
  1005. static var screenWidth: CGFloat {
  1006. UIScreen.main.bounds.width
  1007. }
  1008. }