HomeRootView.swift 50 KB

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