HomeRootView.swift 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  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. currentGlucoseTarget: $state.currentGlucoseTarget,
  121. glucoseColorScheme: $state.glucoseColorScheme,
  122. glucose: state.latestTwoGlucoseValues
  123. ).scaleEffect(0.9)
  124. .onTapGesture {
  125. state.openCGM()
  126. }
  127. .onLongPressGesture {
  128. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  129. impactHeavy.impactOccurred()
  130. state.showModal(for: .snooze)
  131. }
  132. }
  133. var pumpView: some View {
  134. PumpView(
  135. reservoir: $state.reservoir,
  136. name: $state.pumpName,
  137. expiresAtDate: $state.pumpExpiresAtDate,
  138. timerDate: $state.timerDate,
  139. timeZone: $state.timeZone,
  140. pumpStatusHighlightMessage: $state.pumpStatusHighlightMessage,
  141. battery: $state.batteryFromPersistence
  142. ).onTapGesture {
  143. if state.pumpDisplayState == nil {
  144. // shows user confirmation dialog with pump model choices, then proceeds to setup
  145. showPumpSelection.toggle()
  146. } else {
  147. // sends user to pump settings
  148. state.setupPump.toggle()
  149. }
  150. }
  151. }
  152. var tempBasalString: String? {
  153. guard let lastTempBasal = state.tempBasals.last?.tempBasal, let tempRate = lastTempBasal.rate else {
  154. return nil
  155. }
  156. let rateString = numberFormatter.string(from: tempRate as NSNumber) ?? "0"
  157. var manualBasalString = ""
  158. if let apsManager = state.apsManager, apsManager.isManualTempBasal {
  159. manualBasalString = NSLocalizedString(
  160. " - Manual Basal ⚠️",
  161. comment: "Manual Temp basal"
  162. )
  163. }
  164. return rateString + " " + NSLocalizedString(" U/hr", comment: "Unit per hour with space") + manualBasalString
  165. }
  166. var overrideString: String? {
  167. guard let latestOverride = latestOverride.first else {
  168. return nil
  169. }
  170. let percent = latestOverride.percentage
  171. let percentString = percent == 100 ? "" : "\(percent.formatted(.number)) %"
  172. let unit = state.units
  173. var target = (latestOverride.target ?? 100) as Decimal
  174. target = unit == .mmolL ? target.asMmolL : target
  175. var targetString = target == 0 ? "" : (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " + unit
  176. .rawValue
  177. if tempTargetString != nil {
  178. targetString = ""
  179. }
  180. let duration = latestOverride.duration ?? 0
  181. let addedMinutes = Int(truncating: duration)
  182. let date = latestOverride.date ?? Date()
  183. let newDuration = max(
  184. Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes),
  185. 0
  186. )
  187. let indefinite = latestOverride.indefinite
  188. var durationString = ""
  189. if !indefinite {
  190. if newDuration >= 1 {
  191. durationString = formatHrMin(Int(newDuration))
  192. } else if newDuration > 0 {
  193. durationString = "\(Int(newDuration * 60)) 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. currentGlucoseTarget: $state.currentGlucoseTarget,
  310. screenHours: $state.hours,
  311. glucoseColorScheme: $state.glucoseColorScheme,
  312. displayXgridLines: $state.displayXgridLines,
  313. displayYgridLines: $state.displayYgridLines,
  314. thresholdLines: $state.thresholdLines,
  315. state: state
  316. )
  317. }
  318. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: nil))
  319. }
  320. func highlightButtons() {
  321. for i in 0 ..< timeButtons.count {
  322. timeButtons[i].active = timeButtons[i].hours == state.hours
  323. }
  324. }
  325. @ViewBuilder func rightHeaderPanel(_: GeometryProxy) -> some View {
  326. VStack(alignment: .leading, spacing: 20) {
  327. /// Loop view at bottomLeading
  328. LoopView(
  329. closedLoop: $state.closedLoop,
  330. timerDate: $state.timerDate,
  331. isLooping: $state.isLooping,
  332. lastLoopDate: $state.lastLoopDate,
  333. manualTempBasal: $state.manualTempBasal,
  334. determination: state.determinationsFromPersistence
  335. ).onTapGesture {
  336. state.isStatusPopupPresented = true
  337. setStatusTitle()
  338. }.onLongPressGesture {
  339. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  340. impactHeavy.impactOccurred()
  341. state.runLoop()
  342. }
  343. /// eventualBG string at bottomTrailing
  344. if let eventualBG = state.enactedAndNonEnactedDeterminations.first?.eventualBG {
  345. let bg = eventualBG as Decimal
  346. HStack {
  347. Image(systemName: "arrow.right.circle")
  348. .font(.system(size: 16, weight: .bold))
  349. Text(
  350. numberFormatter.string(
  351. from: (
  352. state.units == .mmolL ? bg
  353. .asMmolL : bg
  354. ) as NSNumber
  355. )!
  356. )
  357. .font(.system(size: 16))
  358. }
  359. } else {
  360. HStack {
  361. Image(systemName: "arrow.right.circle")
  362. .font(.system(size: 16, weight: .bold))
  363. Text("--")
  364. .font(.system(size: 16))
  365. }
  366. }
  367. }
  368. }
  369. @ViewBuilder func mealPanel(_: GeometryProxy) -> some View {
  370. HStack {
  371. HStack {
  372. Image(systemName: "syringe.fill")
  373. .font(.system(size: 16))
  374. .foregroundColor(Color.insulin)
  375. Text(
  376. (
  377. numberFormatter
  378. .string(from: (state.enactedAndNonEnactedDeterminations.first?.iob ?? 0) as NSNumber) ?? "0"
  379. ) +
  380. NSLocalizedString(" U", comment: "Insulin unit")
  381. )
  382. .font(.system(size: 16, weight: .bold, design: .rounded))
  383. }
  384. Spacer()
  385. HStack {
  386. Image(systemName: "fork.knife")
  387. .font(.system(size: 16))
  388. .foregroundColor(.loopYellow)
  389. Text(
  390. (
  391. numberFormatter
  392. .string(from: (state.enactedAndNonEnactedDeterminations.first?.cob ?? 0) as NSNumber) ?? "0"
  393. ) +
  394. NSLocalizedString(" g", comment: "gram of carbs")
  395. )
  396. .font(.system(size: 16, weight: .bold, design: .rounded))
  397. }
  398. Spacer()
  399. HStack {
  400. if state.pumpSuspended {
  401. Text("Pump suspended")
  402. .font(.system(size: 12, weight: .bold, design: .rounded)).foregroundColor(.loopGray)
  403. } else if let tempBasalString = tempBasalString {
  404. Image(systemName: "drop.circle")
  405. .font(.system(size: 16))
  406. .foregroundColor(.insulinTintColor)
  407. Text(tempBasalString)
  408. .font(.system(size: 16, weight: .bold, design: .rounded))
  409. } else {
  410. Image(systemName: "drop.circle")
  411. .font(.system(size: 16))
  412. .foregroundColor(.insulinTintColor)
  413. Text("No Data")
  414. .font(.system(size: 16, weight: .bold, design: .rounded))
  415. }
  416. }
  417. if state.totalInsulinDisplayType == .totalDailyDose {
  418. Spacer()
  419. Text(
  420. "TDD: " +
  421. (
  422. numberFormatter
  423. .string(from: (state.determinationsFromPersistence.first?.totalDailyDose ?? 0) as NSNumber) ??
  424. "0"
  425. ) +
  426. NSLocalizedString(" U", comment: "Insulin unit")
  427. )
  428. .font(.system(size: 16, weight: .bold, design: .rounded))
  429. } else {
  430. Spacer()
  431. HStack {
  432. Text(
  433. "TINS: \(state.roundedTotalBolus)" +
  434. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  435. )
  436. .font(.system(size: 16, weight: .bold, design: .rounded))
  437. .onChange(of: state.hours) { _ in
  438. state.roundedTotalBolus = state.calculateTINS()
  439. }
  440. .onAppear {
  441. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  442. state.roundedTotalBolus = state.calculateTINS()
  443. }
  444. }
  445. }
  446. }
  447. }.padding(.horizontal, 10)
  448. }
  449. @ViewBuilder func profileView(geo: GeometryProxy) -> some View {
  450. ZStack {
  451. /// rectangle as background
  452. RoundedRectangle(cornerRadius: 15)
  453. .fill(
  454. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color.insulin
  455. .opacity(0.1)
  456. )
  457. .clipShape(RoundedRectangle(cornerRadius: 15))
  458. .frame(height: geo.size.height * 0.08)
  459. .shadow(
  460. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  461. Color.black.opacity(0.33),
  462. radius: 3
  463. )
  464. HStack {
  465. /// actual profile view
  466. Image(systemName: "person.fill")
  467. .font(.system(size: 25))
  468. Spacer()
  469. if let overrideString = overrideString {
  470. VStack {
  471. Text(latestOverride.first?.name ?? "Custom Override")
  472. .font(.subheadline)
  473. .frame(maxWidth: .infinity, alignment: .leading)
  474. Text("\(overrideString)")
  475. .font(.caption)
  476. .frame(maxWidth: .infinity, alignment: .leading)
  477. }.padding(.leading, 5)
  478. Spacer()
  479. Image(systemName: "xmark.app")
  480. .font(.system(size: 25))
  481. } else {
  482. if tempTargetString == nil {
  483. VStack {
  484. Text("Normal Profile")
  485. .font(.subheadline)
  486. .frame(maxWidth: .infinity, alignment: .leading)
  487. Text("100 %")
  488. .font(.caption)
  489. .frame(maxWidth: .infinity, alignment: .leading)
  490. }.padding(.leading, 5)
  491. Spacer()
  492. /// to ensure the same position....
  493. Image(systemName: "xmark.app")
  494. .font(.system(size: 25))
  495. .foregroundStyle(Color.clear)
  496. }
  497. }
  498. }
  499. .padding(.horizontal, 10)
  500. .confirmationDialog(
  501. "Stop the Override \"\(latestOverride.first?.name ?? "")\"?",
  502. isPresented: $isConfirmStopOverrideShown,
  503. titleVisibility: .visible
  504. ) {
  505. Button("Stop", role: .destructive) {
  506. Task {
  507. guard let objectID = latestOverride.first?.objectID else { return }
  508. await state.cancelOverride(withID: objectID)
  509. }
  510. }
  511. Button("Cancel", role: .cancel) {}
  512. }
  513. .padding(.trailing, 8)
  514. .onTapGesture {
  515. if !latestOverride.isEmpty {
  516. isConfirmStopOverrideShown = true
  517. }
  518. }
  519. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  520. .overlay {
  521. /// just show temp target if no profile is already active
  522. if overrideString == nil, let tempTargetString = tempTargetString {
  523. ZStack {
  524. /// rectangle as background
  525. RoundedRectangle(cornerRadius: 15)
  526. .fill(
  527. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) :
  528. Color
  529. .insulin
  530. .opacity(0.2)
  531. )
  532. .clipShape(RoundedRectangle(cornerRadius: 15))
  533. .frame(height: UIScreen.main.bounds.height / 18)
  534. .shadow(
  535. color: colorScheme == .dark ? Color(
  536. red: 0.02745098039,
  537. green: 0.1098039216,
  538. blue: 0.1411764706
  539. ) :
  540. Color.black.opacity(0.33),
  541. radius: 3
  542. )
  543. HStack {
  544. Image(systemName: "person.fill")
  545. .font(.system(size: 25))
  546. Spacer()
  547. Text(tempTargetString)
  548. .font(.subheadline)
  549. Spacer()
  550. }.padding(.horizontal, 10)
  551. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  552. }
  553. }
  554. }
  555. @ViewBuilder func bolusProgressBar(_ progress: Decimal) -> some View {
  556. GeometryReader { geo in
  557. RoundedRectangle(cornerRadius: 15)
  558. .frame(height: 6)
  559. .foregroundColor(.clear)
  560. .background(
  561. LinearGradient(colors: [
  562. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  563. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  564. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  565. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  566. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  567. ], startPoint: .leading, endPoint: .trailing)
  568. .mask(alignment: .leading) {
  569. RoundedRectangle(cornerRadius: 15)
  570. .frame(width: geo.size.width * CGFloat(progress))
  571. }
  572. )
  573. }
  574. }
  575. @ViewBuilder func bolusView(geo: GeometryProxy, _ progress: Decimal) -> some View {
  576. /// ensure that state.lastPumpBolus has a value, i.e. there is a last bolus done by the pump and not an external bolus
  577. /// - TRUE: show the pump bolus
  578. /// - FALSE: do not show a progress bar at all
  579. if let bolusTotal = state.lastPumpBolus?.bolus?.amount {
  580. let bolusFraction = progress * (bolusTotal as Decimal)
  581. let bolusString =
  582. (bolusProgressFormatter.string(from: bolusFraction as NSNumber) ?? "0")
  583. + " of " +
  584. (numberFormatter.string(from: bolusTotal as NSNumber) ?? "0")
  585. + NSLocalizedString(" U", comment: "Insulin unit")
  586. ZStack {
  587. /// rectangle as background
  588. RoundedRectangle(cornerRadius: 15)
  589. .fill(
  590. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color
  591. .insulin
  592. .opacity(0.2)
  593. )
  594. .clipShape(RoundedRectangle(cornerRadius: 15))
  595. .frame(height: geo.size.height * 0.08)
  596. .shadow(
  597. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  598. Color.black.opacity(0.33),
  599. radius: 3
  600. )
  601. /// actual bolus view
  602. HStack {
  603. Image(systemName: "cross.vial.fill")
  604. .font(.system(size: 25))
  605. Spacer()
  606. VStack {
  607. Text("Bolusing")
  608. .font(.subheadline)
  609. .frame(maxWidth: .infinity, alignment: .leading)
  610. Text(bolusString)
  611. .font(.caption)
  612. .frame(maxWidth: .infinity, alignment: .leading)
  613. }.padding(.leading, 5)
  614. Spacer()
  615. Button {
  616. state.showProgressView()
  617. state.cancelBolus()
  618. } label: {
  619. Image(systemName: "xmark.app")
  620. .font(.system(size: 25))
  621. }
  622. }.padding(.horizontal, 10)
  623. .padding(.trailing, 8)
  624. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  625. .overlay(alignment: .bottom) {
  626. bolusProgressBar(progress).padding(.horizontal, 18).offset(y: 48)
  627. }.clipShape(RoundedRectangle(cornerRadius: 15))
  628. }
  629. }
  630. @ViewBuilder func mainView() -> some View {
  631. GeometryReader { geo in
  632. VStack(spacing: 0) {
  633. ZStack {
  634. /// glucose bobble
  635. glucoseView
  636. /// right panel with loop status and evBG
  637. HStack {
  638. Spacer()
  639. rightHeaderPanel(geo)
  640. }.padding(.trailing, 20)
  641. /// left panel with pump related info
  642. HStack {
  643. pumpView
  644. Spacer()
  645. }.padding(.leading, 20)
  646. }.padding(.top, 10)
  647. mealPanel(geo).padding(.top, UIDevice.adjustPadding(min: nil, max: 30))
  648. .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 20))
  649. mainChart(geo: geo)
  650. timeInterval.padding(.top, UIDevice.adjustPadding(min: 0, max: 12))
  651. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: 12))
  652. if let progress = state.bolusProgress {
  653. bolusView(geo: geo, progress).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  654. } else {
  655. profileView(geo: geo).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  656. }
  657. }
  658. .background(color)
  659. }
  660. .onChange(of: state.hours) { _ in
  661. highlightButtons()
  662. }
  663. .onAppear {
  664. configureView {
  665. highlightButtons()
  666. }
  667. }
  668. .navigationTitle("Home")
  669. .navigationBarHidden(true)
  670. .ignoresSafeArea(.keyboard)
  671. .popup(isPresented: state.isStatusPopupPresented, alignment: .top, direction: .top) {
  672. popup
  673. .padding()
  674. .background(
  675. RoundedRectangle(cornerRadius: 8, style: .continuous)
  676. .fill(colorScheme == .dark ? Color(
  677. "Chart"
  678. ) : Color(UIColor.darkGray))
  679. )
  680. .onTapGesture {
  681. state.isStatusPopupPresented = false
  682. }
  683. .gesture(
  684. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  685. .onEnded { value in
  686. if value.translation.height < 0 {
  687. state.isStatusPopupPresented = false
  688. }
  689. }
  690. )
  691. }
  692. .confirmationDialog("Pump Model", isPresented: $showPumpSelection) {
  693. Button("Medtronic") { state.addPump(.minimed) }
  694. Button("Omnipod Eros") { state.addPump(.omnipod) }
  695. Button("Omnipod Dash") { state.addPump(.omnipodBLE) }
  696. Button("Pump Simulator") { state.addPump(.simulator) }
  697. } message: { Text("Select Pump Model") }
  698. .sheet(isPresented: $state.setupPump) {
  699. if let pumpManager = state.provider.apsManager.pumpManager {
  700. PumpConfig.PumpSettingsView(
  701. pumpManager: pumpManager,
  702. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  703. completionDelegate: state,
  704. setupDelegate: state
  705. )
  706. } else {
  707. PumpConfig.PumpSetupView(
  708. pumpType: state.setupPumpType,
  709. pumpInitialSettings: PumpConfig.PumpInitialSettings.default,
  710. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  711. completionDelegate: state,
  712. setupDelegate: state
  713. )
  714. }
  715. }
  716. .sheet(isPresented: $state.isLegendPresented) {
  717. NavigationStack {
  718. Text(
  719. "The oref algorithm determines insulin dosing based on a number of scenarios that it estimates with different types of forecasts."
  720. )
  721. .font(.subheadline)
  722. .foregroundColor(.secondary)
  723. if state.forecastDisplayType == .lines {
  724. List {
  725. DefinitionRow(
  726. term: "IOB (Insulin on Board)",
  727. definition: "Forecasts BG based on the amount of insulin still active in the body.",
  728. color: .insulin
  729. )
  730. DefinitionRow(
  731. term: "ZT (Zero-Temp)",
  732. definition: "Forecasts the worst-case blood glucose (BG) scenario if no carbs are absorbed and insulin delivery is stopped until BG starts rising.",
  733. color: .zt
  734. )
  735. DefinitionRow(
  736. term: "COB (Carbs on Board)",
  737. definition: "Forecasts BG changes by considering the amount of carbohydrates still being absorbed in the body.",
  738. color: .loopYellow
  739. )
  740. DefinitionRow(
  741. term: "UAM (Unannounced Meal)",
  742. definition: "Forecasts BG levels and insulin dosing needs for unexpected meals or other causes of BG rises without prior notice.",
  743. color: .uam
  744. )
  745. }
  746. .padding(.trailing, 10)
  747. .navigationBarTitle("Legend", displayMode: .inline)
  748. } else {
  749. List {
  750. DefinitionRow(
  751. term: "Cone of Uncertainty",
  752. 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.",
  753. color: Color.blue.opacity(0.5)
  754. )
  755. }
  756. .padding(.trailing, 10)
  757. .navigationBarTitle("Legend", displayMode: .inline)
  758. }
  759. Button { state.isLegendPresented.toggle() }
  760. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  761. .buttonStyle(.bordered)
  762. .padding(.top)
  763. }
  764. .padding()
  765. .presentationDetents(
  766. [.fraction(0.9), .large],
  767. selection: $state.legendSheetDetent
  768. )
  769. }
  770. }
  771. @State var settingsPath = NavigationPath()
  772. @ViewBuilder func tabBar() -> some View {
  773. ZStack(alignment: .bottom) {
  774. TabView(selection: $selectedTab) {
  775. let carbsRequiredBadge: String? = {
  776. guard let carbsRequired = state.enactedAndNonEnactedDeterminations.first?.carbsRequired,
  777. state.showCarbsRequiredBadge
  778. else {
  779. return nil
  780. }
  781. let carbsRequiredDecimal = Decimal(carbsRequired)
  782. if carbsRequiredDecimal > state.settingsManager.settings.carbsRequiredThreshold {
  783. let numberAsNSNumber = NSDecimalNumber(decimal: carbsRequiredDecimal)
  784. return (numberFormatter.string(from: numberAsNSNumber) ?? "") + " g"
  785. }
  786. return nil
  787. }()
  788. NavigationStack { mainView() }
  789. .tabItem { Label("Main", systemImage: "chart.xyaxis.line") }
  790. .badge(carbsRequiredBadge).tag(0)
  791. NavigationStack { DataTable.RootView(resolver: resolver) }
  792. .tabItem { Label("History", systemImage: historySFSymbol) }.tag(1)
  793. Spacer()
  794. NavigationStack { OverrideConfig.RootView(resolver: resolver) }
  795. .tabItem {
  796. Label(
  797. "Adjustments",
  798. systemImage: "slider.horizontal.2.gobackward"
  799. ) }.tag(2)
  800. NavigationStack(path: self.$settingsPath) {
  801. Settings.RootView(resolver: resolver) }
  802. .tabItem { Label(
  803. "Settings",
  804. systemImage: "gear"
  805. ) }.tag(3)
  806. }
  807. .tint(Color.tabBar)
  808. Button(
  809. action: {
  810. state.showModal(for: .bolus) },
  811. label: {
  812. Image(systemName: "plus.circle.fill")
  813. .font(.system(size: 40))
  814. .foregroundStyle(Color.tabBar)
  815. .padding(.bottom, 1)
  816. .padding(.horizontal, 20)
  817. }
  818. )
  819. }.ignoresSafeArea(.keyboard, edges: .bottom).blur(radius: state.waitForSuggestion ? 8 : 0)
  820. .onChange(of: selectedTab) { _ in
  821. print("current path is empty: \(settingsPath.isEmpty)")
  822. settingsPath = NavigationPath()
  823. }
  824. }
  825. var body: some View {
  826. ZStack(alignment: .center) {
  827. tabBar()
  828. if state.waitForSuggestion {
  829. CustomProgressView(text: "Updating IOB...")
  830. }
  831. }
  832. }
  833. private func parseReasonConclusion(_ reasonConclusion: String, isMmolL: Bool) -> String {
  834. var updatedConclusion = reasonConclusion
  835. // Handle "minGuardBG x<y" pattern
  836. if let range = updatedConclusion.range(of: "minGuardBG\\s*-?\\d+<\\d+", options: .regularExpression) {
  837. let matchedString = updatedConclusion[range]
  838. let parts = matchedString.components(separatedBy: "<")
  839. if let firstValue = Double(parts[0].components(separatedBy: CharacterSet.decimalDigits.inverted).joined()),
  840. let secondValue = Double(parts[1])
  841. {
  842. let formattedFirstValue = isMmolL ? Double(firstValue.asMmolL) : firstValue
  843. let formattedSecondValue = isMmolL ? Double(secondValue.asMmolL) : secondValue
  844. let formattedString = "minGuardBG \(formattedFirstValue)<\(formattedSecondValue)"
  845. updatedConclusion = updatedConclusion.replacingOccurrences(of: matchedString, with: formattedString)
  846. }
  847. }
  848. // Handle "Eventual BG x >= target" pattern
  849. if let range = updatedConclusion.range(of: "Eventual BG\\s*\\d+\\s*>?=\\s*\\d+", options: .regularExpression) {
  850. let matchedString = updatedConclusion[range]
  851. let parts = matchedString.components(separatedBy: " >= ")
  852. if let firstValue = Double(parts[0].components(separatedBy: CharacterSet.decimalDigits.inverted).joined()),
  853. let secondValue = Double(parts[1])
  854. {
  855. let formattedFirstValue = isMmolL ? Double(firstValue.asMmolL) : firstValue
  856. let formattedSecondValue = isMmolL ? Double(secondValue.asMmolL) : secondValue
  857. let formattedString = "Eventual BG \(formattedFirstValue) >= \(formattedSecondValue)"
  858. updatedConclusion = updatedConclusion.replacingOccurrences(of: matchedString, with: formattedString)
  859. }
  860. }
  861. return updatedConclusion.capitalizingFirstLetter()
  862. }
  863. private var popup: some View {
  864. VStack(alignment: .leading, spacing: 4) {
  865. Text(statusTitle).font(.headline).foregroundColor(.white)
  866. .padding(.bottom, 4)
  867. if let determination = state.determinationsFromPersistence.first {
  868. if determination.glucose == 400 {
  869. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  870. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  871. } else {
  872. let tags = !state.isSmoothingEnabled ? determination.reasonParts : determination
  873. .reasonParts + ["Smoothing: On"]
  874. TagCloudView(
  875. tags: tags,
  876. shouldParseToMmolL: state.units == .mmolL
  877. )
  878. .animation(.none, value: false)
  879. Text(
  880. self
  881. .parseReasonConclusion(
  882. determination.reasonConclusion,
  883. isMmolL: state.units == .mmolL
  884. )
  885. ).font(.caption).foregroundColor(.white)
  886. }
  887. } else {
  888. Text("No determination found").font(.body).foregroundColor(.white)
  889. }
  890. if let errorMessage = state.errorMessage, let date = state.errorDate {
  891. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  892. .foregroundColor(.white)
  893. .font(.headline)
  894. .padding(.bottom, 4)
  895. .padding(.top, 8)
  896. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  897. }
  898. }
  899. }
  900. private func setStatusTitle() {
  901. if let determination = state.determinationsFromPersistence.first {
  902. let dateFormatter = DateFormatter()
  903. dateFormatter.timeStyle = .short
  904. statusTitle = NSLocalizedString("Oref Determination enacted at", comment: "Headline in enacted pop up") +
  905. " " +
  906. dateFormatter
  907. .string(from: determination.deliverAt ?? Date())
  908. } else {
  909. statusTitle = "No Oref determination"
  910. return
  911. }
  912. }
  913. }
  914. }
  915. extension UIDevice {
  916. public enum DeviceSize: CGFloat {
  917. case smallDevice = 667 // Height for 4" iPhone SE
  918. case largeDevice = 852 // Height for 6.1" iPhone 15 Pro
  919. }
  920. @usableFromInline static func adjustPadding(min: CGFloat? = nil, max: CGFloat? = nil) -> CGFloat? {
  921. if UIScreen.screenHeight > UIDevice.DeviceSize.smallDevice.rawValue {
  922. if UIScreen.screenHeight >= UIDevice.DeviceSize.largeDevice.rawValue {
  923. return max
  924. } else {
  925. return min != nil ?
  926. (max != nil ? max! * (UIScreen.screenHeight / UIDevice.DeviceSize.largeDevice.rawValue) : nil) : nil
  927. }
  928. } else {
  929. return min
  930. }
  931. }
  932. }
  933. extension UIScreen {
  934. static var screenHeight: CGFloat {
  935. UIScreen.main.bounds.height
  936. }
  937. static var screenWidth: CGFloat {
  938. UIScreen.main.bounds.width
  939. }
  940. }
  941. // Helper function to convert a start and end hour to either 24-hour or AM/PM format
  942. func formatTimeRange(start: String?, end: String?) -> String {
  943. guard let start = start, let end = end else {
  944. return ""
  945. }
  946. // Check if the format is 24-hour or AM/PM
  947. if is24HourFormat() {
  948. // Return the original 24-hour format
  949. return "\(start)-\(end)"
  950. } else {
  951. // Convert to AM/PM format using DateFormatter
  952. let formatter = DateFormatter()
  953. formatter.dateFormat = "HH"
  954. if let startHour = Int(start), let endHour = Int(end) {
  955. let startDate = Calendar.current.date(bySettingHour: startHour, minute: 0, second: 0, of: Date()) ?? Date()
  956. let endDate = Calendar.current.date(bySettingHour: endHour, minute: 0, second: 0, of: Date()) ?? Date()
  957. // Customize the format to "2p" or "2a"
  958. formatter.dateFormat = "ha"
  959. let startFormatted = formatter.string(from: startDate).lowercased().replacingOccurrences(of: "m", with: "")
  960. let endFormatted = formatter.string(from: endDate).lowercased().replacingOccurrences(of: "m", with: "")
  961. return "\(startFormatted)-\(endFormatted)"
  962. } else {
  963. return ""
  964. }
  965. }
  966. }