HomeRootView.swift 50 KB

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