HomeRootView.swift 48 KB

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