HomeRootView.swift 47 KB

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