HomeRootView.swift 50 KB

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