HomeRootView.swift 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. import CoreData
  2. import SpriteKit
  3. import SwiftDate
  4. import SwiftUI
  5. import Swinject
  6. extension Home {
  7. struct RootView: BaseView {
  8. let resolver: Resolver
  9. @StateObject var state = StateModel()
  10. @State var isStatusPopupPresented = false
  11. @State var showCancelAlert = false
  12. @State var isMenuPresented = false
  13. @State var showTreatments = false
  14. @State var selectedTab: Int = 0
  15. @State private var statusTitle: String = ""
  16. struct Buttons: Identifiable {
  17. let label: String
  18. let number: String
  19. var active: Bool
  20. let hours: Int16
  21. var id: String { label }
  22. }
  23. @State var timeButtons: [Buttons] = [
  24. Buttons(label: "2 hours", number: "2", active: false, hours: 2),
  25. Buttons(label: "4 hours", number: "4", active: false, hours: 4),
  26. Buttons(label: "6 hours", number: "6", active: false, hours: 6),
  27. Buttons(label: "12 hours", number: "12", active: false, hours: 12),
  28. Buttons(label: "24 hours", number: "24", active: false, hours: 24)
  29. ]
  30. let buttonFont = Font.custom("TimeButtonFont", size: 14)
  31. @Environment(\.managedObjectContext) var moc
  32. @Environment(\.colorScheme) var colorScheme
  33. @FetchRequest(
  34. entity: Override.entity(),
  35. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  36. ) var fetchedPercent: FetchedResults<Override>
  37. @FetchRequest(
  38. entity: OrefDetermination.entity(),
  39. sortDescriptors: [NSSortDescriptor(key: "deliverAt", ascending: false)],
  40. predicate: NSPredicate.predicateFor30MinAgoForDetermination,
  41. animation: Animation.bouncy
  42. ) var determination: FetchedResults<OrefDetermination>
  43. @FetchRequest(
  44. entity: OverridePresets.entity(),
  45. sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)], predicate: NSPredicate(
  46. format: "name != %@", "" as String
  47. )
  48. ) var fetchedProfiles: FetchedResults<OverridePresets>
  49. @FetchRequest(
  50. entity: TempTargets.entity(),
  51. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  52. ) var sliderTTpresets: FetchedResults<TempTargets>
  53. @FetchRequest(
  54. entity: TempTargetsSlider.entity(),
  55. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  56. ) var enactedSliderTT: FetchedResults<TempTargetsSlider>
  57. @FetchRequest(
  58. entity: GlucoseStored.entity(),
  59. sortDescriptors: [NSSortDescriptor(keyPath: \GlucoseStored.date, ascending: true)],
  60. predicate: NSPredicate.predicateFor30MinAgo,
  61. animation: Animation.bouncy
  62. ) var glucoseFromPersistence: FetchedResults<GlucoseStored>
  63. var bolusProgressFormatter: NumberFormatter {
  64. let formatter = NumberFormatter()
  65. formatter.numberStyle = .decimal
  66. formatter.minimum = 0
  67. formatter.maximumFractionDigits = state.settingsManager.preferences.bolusIncrement > 0.05 ? 1 : 2
  68. formatter.minimumFractionDigits = state.settingsManager.preferences.bolusIncrement > 0.05 ? 1 : 2
  69. formatter.allowsFloats = true
  70. formatter.roundingIncrement = Double(state.settingsManager.preferences.bolusIncrement) as NSNumber
  71. return formatter
  72. }
  73. private var numberFormatter: NumberFormatter {
  74. let formatter = NumberFormatter()
  75. formatter.numberStyle = .decimal
  76. formatter.maximumFractionDigits = 2
  77. return formatter
  78. }
  79. private var fetchedTargetFormatter: NumberFormatter {
  80. let formatter = NumberFormatter()
  81. formatter.numberStyle = .decimal
  82. if state.units == .mmolL {
  83. formatter.maximumFractionDigits = 1
  84. } else { formatter.maximumFractionDigits = 0 }
  85. return formatter
  86. }
  87. private var targetFormatter: NumberFormatter {
  88. let formatter = NumberFormatter()
  89. formatter.numberStyle = .decimal
  90. formatter.maximumFractionDigits = 1
  91. return formatter
  92. }
  93. private var tirFormatter: NumberFormatter {
  94. let formatter = NumberFormatter()
  95. formatter.numberStyle = .decimal
  96. formatter.maximumFractionDigits = 0
  97. return formatter
  98. }
  99. private var dateFormatter: DateFormatter {
  100. let dateFormatter = DateFormatter()
  101. dateFormatter.timeStyle = .short
  102. return dateFormatter
  103. }
  104. private var spriteScene: SKScene {
  105. let scene = SnowScene()
  106. scene.scaleMode = .resizeFill
  107. scene.backgroundColor = .clear
  108. return scene
  109. }
  110. private var color: LinearGradient {
  111. colorScheme == .dark ? LinearGradient(
  112. gradient: Gradient(colors: [
  113. Color.bgDarkBlue,
  114. Color.bgDarkerDarkBlue
  115. ]),
  116. startPoint: .top,
  117. endPoint: .bottom
  118. )
  119. :
  120. LinearGradient(
  121. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  122. startPoint: .top,
  123. endPoint: .bottom
  124. )
  125. }
  126. private var historySFSymbol: String {
  127. if #available(iOS 17.0, *) {
  128. return "book.pages"
  129. } else {
  130. return "book"
  131. }
  132. }
  133. var glucoseView: some View {
  134. CurrentGlucoseView(
  135. timerDate: $state.timerDate,
  136. delta: $state.glucoseDelta,
  137. units: $state.units,
  138. alarm: $state.alarm,
  139. lowGlucose: $state.lowGlucose,
  140. highGlucose: $state.highGlucose
  141. ).scaleEffect(0.9)
  142. .onTapGesture {
  143. if state.alarm == nil {
  144. state.openCGM()
  145. } else {
  146. state.showModal(for: .snooze)
  147. }
  148. }
  149. .onLongPressGesture {
  150. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  151. impactHeavy.impactOccurred()
  152. if state.alarm == nil {
  153. state.showModal(for: .snooze)
  154. } else {
  155. state.openCGM()
  156. }
  157. }
  158. }
  159. var pumpView: some View {
  160. PumpView(
  161. reservoir: $state.reservoir,
  162. battery: $state.battery,
  163. name: $state.pumpName,
  164. expiresAtDate: $state.pumpExpiresAtDate,
  165. timerDate: $state.timerDate,
  166. timeZone: $state.timeZone,
  167. state: state
  168. ).onTapGesture {
  169. if state.pumpDisplayState != nil {
  170. state.setupPump = true
  171. }
  172. }
  173. }
  174. var tempBasalString: String? {
  175. guard let tempRate = state.tempRate else {
  176. return nil
  177. }
  178. let rateString = numberFormatter.string(from: tempRate as NSNumber) ?? "0"
  179. var manualBasalString = ""
  180. if state.apsManager.isManualTempBasal {
  181. manualBasalString = NSLocalizedString(
  182. " - Manual Basal ⚠️",
  183. comment: "Manual Temp basal"
  184. )
  185. }
  186. return rateString + " " + NSLocalizedString(" U/hr", comment: "Unit per hour with space") + manualBasalString
  187. }
  188. var tempTargetString: String? {
  189. guard let tempTarget = state.tempTarget else {
  190. return nil
  191. }
  192. let target = tempTarget.targetBottom ?? 0
  193. let unitString = targetFormatter.string(from: (tempTarget.targetBottom?.asMmolL ?? 0) as NSNumber) ?? ""
  194. let rawString = (tirFormatter.string(from: (tempTarget.targetBottom ?? 0) as NSNumber) ?? "") + " " + state.units
  195. .rawValue
  196. var string = ""
  197. if sliderTTpresets.first?.active ?? false {
  198. let hbt = sliderTTpresets.first?.hbt ?? 0
  199. string = ", " + (tirFormatter.string(from: state.infoPanelTTPercentage(hbt, target) as NSNumber) ?? "") + " %"
  200. }
  201. let percentString = state
  202. .units == .mmolL ? (unitString + " mmol/L" + string) : (rawString + (string == "0" ? "" : string))
  203. return tempTarget.displayName + " " + percentString
  204. }
  205. var overrideString: String? {
  206. guard fetchedPercent.first?.enabled ?? false else {
  207. return nil
  208. }
  209. var percentString = "\((fetchedPercent.first?.percentage ?? 100).formatted(.number)) %"
  210. var target = (fetchedPercent.first?.target ?? 100) as Decimal
  211. let indefinite = (fetchedPercent.first?.indefinite ?? false)
  212. let unit = state.units.rawValue
  213. if state.units == .mmolL {
  214. target = target.asMmolL
  215. }
  216. var targetString = (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " + unit
  217. if tempTargetString != nil || target == 0 { targetString = "" }
  218. percentString = percentString == "100 %" ? "" : percentString
  219. let duration = (fetchedPercent.first?.duration ?? 0) as Decimal
  220. let addedMinutes = Int(duration)
  221. let date = fetchedPercent.first?.date ?? Date()
  222. var newDuration: Decimal = 0
  223. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) > Date() {
  224. newDuration = Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes)
  225. }
  226. var durationString = indefinite ?
  227. "" : newDuration >= 1 ?
  228. (newDuration.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) + " min") :
  229. (
  230. newDuration > 0 ? (
  231. (newDuration * 60).formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) + " s"
  232. ) :
  233. ""
  234. )
  235. let smbToggleString = (fetchedPercent.first?.smbIsOff ?? false) ? " \u{20e0}" : ""
  236. var comma1 = ", "
  237. var comma2 = comma1
  238. var comma3 = comma1
  239. if targetString == "" || percentString == "" { comma1 = "" }
  240. if durationString == "" { comma2 = "" }
  241. if smbToggleString == "" { comma3 = "" }
  242. if percentString == "", targetString == "" {
  243. comma1 = ""
  244. comma2 = ""
  245. }
  246. if percentString == "", targetString == "", smbToggleString == "" {
  247. durationString = ""
  248. comma1 = ""
  249. comma2 = ""
  250. comma3 = ""
  251. }
  252. if durationString == "" {
  253. comma2 = ""
  254. }
  255. if smbToggleString == "" {
  256. comma3 = ""
  257. }
  258. if durationString == "", !indefinite {
  259. return nil
  260. }
  261. return percentString + comma1 + targetString + comma2 + durationString + comma3 + smbToggleString
  262. }
  263. var infoPanel: some View {
  264. HStack(alignment: .center) {
  265. if state.pumpSuspended {
  266. Text("Pump suspended")
  267. .font(.system(size: 15, weight: .bold)).foregroundColor(.loopGray)
  268. .padding(.leading, 8)
  269. } else if let tempBasalString = tempBasalString {
  270. Text(tempBasalString)
  271. .font(.system(size: 15, weight: .bold))
  272. .foregroundColor(.insulin)
  273. .padding(.leading, 8)
  274. }
  275. if state.tins {
  276. Text(
  277. "TINS: \(state.calculateTINS())" +
  278. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  279. )
  280. .font(.system(size: 15, weight: .bold))
  281. .foregroundColor(.insulin)
  282. }
  283. if let tempTargetString = tempTargetString {
  284. Text(tempTargetString)
  285. .font(.caption)
  286. .foregroundColor(.secondary)
  287. }
  288. Spacer()
  289. if state.closedLoop, state.settingsManager.preferences.maxIOB == 0 {
  290. Text("Max IOB: 0").font(.callout).foregroundColor(.orange).padding(.trailing, 20)
  291. }
  292. }
  293. .frame(maxWidth: .infinity, maxHeight: 30)
  294. }
  295. var timeInterval: some View {
  296. HStack(alignment: .center) {
  297. ForEach(timeButtons) { button in
  298. Text(button.active ? NSLocalizedString(button.label, comment: "") : button.number).onTapGesture {
  299. state.hours = button.hours
  300. }
  301. .foregroundStyle(button.active ? (colorScheme == .dark ? Color.white : Color.black).opacity(0.9) : .secondary)
  302. .frame(maxHeight: 30).padding(.horizontal, 8)
  303. .background(
  304. button.active ?
  305. // RGB(30, 60, 95)
  306. (
  307. colorScheme == .dark ? Color(red: 0.1176470588, green: 0.2352941176, blue: 0.3725490196) :
  308. Color.white
  309. ) :
  310. Color
  311. .clear
  312. )
  313. .cornerRadius(20)
  314. }
  315. }
  316. .shadow(
  317. color: Color.black.opacity(colorScheme == .dark ? 0.75 : 0.33),
  318. radius: colorScheme == .dark ? 5 : 3
  319. )
  320. .font(buttonFont)
  321. }
  322. var mainChart: some View {
  323. ZStack {
  324. if state.animatedBackground {
  325. SpriteView(scene: spriteScene, options: [.allowsTransparency])
  326. .ignoresSafeArea()
  327. .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
  328. }
  329. MainChartView(
  330. glucose: $state.glucose,
  331. manualGlucose: $state.manualGlucose,
  332. fpusForChart: $state.fpusForChart,
  333. units: $state.units,
  334. eventualBG: $state.eventualBG,
  335. suggestion: $state.suggestion,
  336. tempBasals: $state.tempBasals,
  337. boluses: $state.boluses,
  338. suspensions: $state.suspensions,
  339. announcement: $state.announcement,
  340. hours: .constant(state.filteredHours),
  341. maxBasal: $state.maxBasal,
  342. autotunedBasalProfile: $state.autotunedBasalProfile,
  343. basalProfile: $state.basalProfile,
  344. tempTargets: $state.tempTargets,
  345. smooth: $state.smooth,
  346. highGlucose: $state.highGlucose,
  347. lowGlucose: $state.lowGlucose,
  348. screenHours: $state.hours,
  349. displayXgridLines: $state.displayXgridLines,
  350. displayYgridLines: $state.displayYgridLines,
  351. thresholdLines: $state.thresholdLines,
  352. isTempTargetActive: $state.isTempTargetActive
  353. )
  354. }
  355. .padding(.bottom)
  356. }
  357. private func selectedProfile() -> (name: String, isOn: Bool) {
  358. var profileString = ""
  359. var display: Bool = false
  360. let duration = (fetchedPercent.first?.duration ?? 0) as Decimal
  361. let indefinite = fetchedPercent.first?.indefinite ?? false
  362. let addedMinutes = Int(duration)
  363. let date = fetchedPercent.first?.date ?? Date()
  364. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) > Date() || indefinite {
  365. display.toggle()
  366. }
  367. if fetchedPercent.first?.enabled ?? false, !(fetchedPercent.first?.isPreset ?? false), display {
  368. profileString = NSLocalizedString("Custom Profile", comment: "Custom but unsaved Profile")
  369. } else if !(fetchedPercent.first?.enabled ?? false) || !display {
  370. profileString = NSLocalizedString("Normal Profile", comment: "Your normal Profile. Use a short string")
  371. } else {
  372. let id_ = fetchedPercent.first?.id ?? ""
  373. let profile = fetchedProfiles.filter({ $0.id == id_ }).first
  374. if profile != nil {
  375. profileString = profile?.name?.description ?? ""
  376. }
  377. }
  378. return (name: profileString, isOn: display)
  379. }
  380. func highlightButtons() {
  381. for i in 0 ..< timeButtons.count {
  382. timeButtons[i].active = timeButtons[i].hours == state.hours
  383. }
  384. }
  385. @ViewBuilder func rightHeaderPanel(_: GeometryProxy) -> some View {
  386. VStack(alignment: .leading, spacing: 20) {
  387. /// Loop view at bottomLeading
  388. LoopView(
  389. closedLoop: $state.closedLoop,
  390. timerDate: $state.timerDate,
  391. isLooping: $state.isLooping,
  392. lastLoopDate: $state.lastLoopDate,
  393. manualTempBasal: $state.manualTempBasal
  394. ).onTapGesture {
  395. state.isStatusPopupPresented = true
  396. setStatusTitle()
  397. }.onLongPressGesture {
  398. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  399. impactHeavy.impactOccurred()
  400. state.runLoop()
  401. }
  402. /// eventualBG string at bottomTrailing
  403. if let eventualBG = state.eventualBG {
  404. HStack {
  405. Image(systemName: "arrow.right.circle")
  406. .font(.system(size: 16, weight: .bold))
  407. Text(
  408. numberFormatter.string(
  409. from: (
  410. state.units == .mmolL ? eventualBG
  411. .asMmolL : Decimal(eventualBG)
  412. ) as NSNumber
  413. )!
  414. )
  415. .font(.system(size: 16))
  416. }
  417. }
  418. }
  419. }
  420. @ViewBuilder func mealPanel(_: GeometryProxy) -> some View {
  421. HStack {
  422. HStack {
  423. Image(systemName: "syringe.fill")
  424. .font(.system(size: 16))
  425. .foregroundColor(Color.insulin)
  426. Text(
  427. (numberFormatter.string(from: (determination.first?.iob ?? 0) as NSNumber) ?? "0") +
  428. NSLocalizedString(" U", comment: "Insulin unit")
  429. )
  430. .font(.system(size: 16, weight: .bold, design: .rounded))
  431. }
  432. Spacer()
  433. HStack {
  434. Image(systemName: "fork.knife")
  435. .font(.system(size: 16))
  436. .foregroundColor(.loopYellow)
  437. Text(
  438. (numberFormatter.string(from: (determination.first?.cob ?? 0) as NSNumber) ?? "0") +
  439. NSLocalizedString(" g", comment: "gram of carbs")
  440. )
  441. .font(.system(size: 16, weight: .bold, design: .rounded))
  442. }
  443. Spacer()
  444. HStack {
  445. if state.pumpSuspended {
  446. Text("Pump suspended")
  447. .font(.system(size: 12, weight: .bold, design: .rounded)).foregroundColor(.loopGray)
  448. } else if let tempBasalString = tempBasalString {
  449. Image(systemName: "drop.circle")
  450. .font(.system(size: 16))
  451. .foregroundColor(.insulinTintColor)
  452. Text(tempBasalString)
  453. .font(.system(size: 16, weight: .bold, design: .rounded))
  454. }
  455. }
  456. if !state.tins {
  457. Spacer()
  458. Text(
  459. "TDD: " + (numberFormatter.string(from: (determination.first?.totalDailyDose ?? 0) as NSNumber) ?? "0") +
  460. NSLocalizedString(" U", comment: "Insulin unit")
  461. )
  462. .font(.system(size: 16, weight: .bold, design: .rounded))
  463. } else {
  464. Spacer()
  465. HStack {
  466. Text(
  467. "TINS: \(state.roundedTotalBolus)" +
  468. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  469. )
  470. .font(.system(size: 16, weight: .bold, design: .rounded))
  471. .onChange(of: state.hours) { _ in
  472. state.roundedTotalBolus = state.calculateTINS()
  473. }
  474. .onAppear {
  475. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  476. state.roundedTotalBolus = state.calculateTINS()
  477. }
  478. }
  479. }
  480. }
  481. }.padding(.horizontal, 10)
  482. }
  483. @ViewBuilder func profileView(_: GeometryProxy) -> some View {
  484. ZStack {
  485. /// rectangle as background
  486. RoundedRectangle(cornerRadius: 15)
  487. .fill(
  488. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color.insulin
  489. .opacity(0.1)
  490. )
  491. .clipShape(RoundedRectangle(cornerRadius: 15))
  492. .frame(height: UIScreen.main.bounds.height / 18)
  493. .shadow(
  494. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  495. Color.black.opacity(0.33),
  496. radius: 3
  497. )
  498. HStack {
  499. /// actual profile view
  500. Image(systemName: "person.fill")
  501. .font(.system(size: 25))
  502. Spacer()
  503. if let overrideString = overrideString {
  504. VStack {
  505. Text(selectedProfile().name)
  506. .font(.subheadline)
  507. .frame(maxWidth: .infinity, alignment: .leading)
  508. Text(overrideString)
  509. .font(.caption)
  510. .frame(maxWidth: .infinity, alignment: .leading)
  511. }.padding(.leading, 5)
  512. Spacer()
  513. Image(systemName: "xmark.app")
  514. .font(.system(size: 25))
  515. } else {
  516. if tempTargetString == nil {
  517. VStack {
  518. Text(selectedProfile().name)
  519. .font(.subheadline)
  520. .frame(maxWidth: .infinity, alignment: .leading)
  521. Text("100 %")
  522. .font(.caption)
  523. .frame(maxWidth: .infinity, alignment: .leading)
  524. }.padding(.leading, 5)
  525. Spacer()
  526. /// to ensure the same position....
  527. Image(systemName: "xmark.app")
  528. .font(.system(size: 25))
  529. .foregroundStyle(Color.clear)
  530. }
  531. }
  532. }.padding(.horizontal, 10)
  533. .alert(
  534. "Return to Normal?", isPresented: $showCancelAlert,
  535. actions: {
  536. Button("No", role: .cancel) {}
  537. Button("Yes", role: .destructive) {
  538. state.cancelProfile()
  539. }
  540. }, message: { Text("This will change settings back to your normal profile.") }
  541. )
  542. .padding(.trailing, 8)
  543. .onTapGesture {
  544. if selectedProfile().name != "Normal Profile" {
  545. showCancelAlert = true
  546. }
  547. }
  548. }.padding(.horizontal, 10).padding(.bottom, 10)
  549. .overlay {
  550. /// just show temp target if no profile is already active
  551. if overrideString == nil, let tempTargetString = tempTargetString {
  552. ZStack {
  553. /// rectangle as background
  554. RoundedRectangle(cornerRadius: 15)
  555. .fill(
  556. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) :
  557. Color
  558. .insulin
  559. .opacity(0.2)
  560. )
  561. .clipShape(RoundedRectangle(cornerRadius: 15))
  562. .frame(height: UIScreen.main.bounds.height / 18)
  563. .shadow(
  564. color: colorScheme == .dark ? Color(
  565. red: 0.02745098039,
  566. green: 0.1098039216,
  567. blue: 0.1411764706
  568. ) :
  569. Color.black.opacity(0.33),
  570. radius: 3
  571. )
  572. HStack {
  573. Image(systemName: "person.fill")
  574. .font(.system(size: 25))
  575. Spacer()
  576. Text(tempTargetString)
  577. .font(.subheadline)
  578. Spacer()
  579. }.padding(.horizontal, 10)
  580. }.padding(.horizontal, 10).padding(.bottom, 10)
  581. }
  582. }
  583. }
  584. @ViewBuilder func bolusProgressBar(_ progress: Decimal) -> some View {
  585. GeometryReader { geo in
  586. RoundedRectangle(cornerRadius: 15)
  587. .frame(height: 6)
  588. .foregroundColor(.clear)
  589. .background(
  590. LinearGradient(colors: [
  591. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  592. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  593. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  594. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  595. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  596. ], startPoint: .leading, endPoint: .trailing)
  597. .mask(alignment: .leading) {
  598. RoundedRectangle(cornerRadius: 15)
  599. .frame(width: geo.size.width * CGFloat(progress))
  600. }
  601. )
  602. }
  603. }
  604. @ViewBuilder func bolusView(_: GeometryProxy, _ progress: Decimal) -> some View {
  605. let bolusTotal = state.boluses.last?.amount ?? 0
  606. let bolusFraction = progress * bolusTotal
  607. let bolusString =
  608. (bolusProgressFormatter.string(from: bolusFraction as NSNumber) ?? "0")
  609. + " of " +
  610. (numberFormatter.string(from: bolusTotal as NSNumber) ?? "0")
  611. + NSLocalizedString(" U", comment: "Insulin unit")
  612. ZStack {
  613. /// rectangle as background
  614. RoundedRectangle(cornerRadius: 15)
  615. .fill(
  616. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color.insulin
  617. .opacity(0.2)
  618. )
  619. .clipShape(RoundedRectangle(cornerRadius: 15))
  620. .frame(height: UIScreen.main.bounds.height / 18)
  621. .shadow(
  622. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  623. Color.black.opacity(0.33),
  624. radius: 3
  625. )
  626. /// actual bolus view
  627. HStack {
  628. Image(systemName: "cross.vial.fill")
  629. .font(.system(size: 25))
  630. Spacer()
  631. VStack {
  632. Text("Bolusing")
  633. .font(.subheadline)
  634. .frame(maxWidth: .infinity, alignment: .leading)
  635. Text(bolusString)
  636. .font(.caption)
  637. .frame(maxWidth: .infinity, alignment: .leading)
  638. }.padding(.leading, 5)
  639. Spacer()
  640. Button {
  641. state.waitForSuggestion = true
  642. state.cancelBolus()
  643. } label: {
  644. Image(systemName: "xmark.app")
  645. .font(.system(size: 25))
  646. }
  647. }.padding(.horizontal, 10)
  648. .padding(.trailing, 8)
  649. }.padding(.horizontal, 10).padding(.bottom, 10)
  650. .overlay(alignment: .bottom) {
  651. bolusProgressBar(progress).padding(.horizontal, 18).offset(y: 45)
  652. }.clipShape(RoundedRectangle(cornerRadius: 15))
  653. }
  654. @ViewBuilder func mainView() -> some View {
  655. GeometryReader { geo in
  656. VStack(spacing: 0) {
  657. // Spacer()
  658. // .frame(height: UIScreen.main.bounds.height / 40)
  659. ZStack {
  660. /// glucose bobble
  661. glucoseView
  662. /// right panel with loop status and evBG
  663. HStack {
  664. Spacer()
  665. rightHeaderPanel(geo)
  666. }.padding(.trailing, 20)
  667. /// left panel with pump related info
  668. HStack {
  669. pumpView
  670. Spacer()
  671. }.padding(.leading, 20)
  672. }.padding(.top, 10)
  673. mealPanel(geo).padding(.top, 30).padding(.bottom, 20)
  674. mainChart
  675. timeInterval.padding(.top, 20).padding(.bottom, 40)
  676. if let progress = state.bolusProgress {
  677. bolusView(geo, progress).padding(.bottom, 10)
  678. } else {
  679. profileView(geo).padding(.bottom, 10)
  680. }
  681. }
  682. .background(color)
  683. }
  684. .onChange(of: state.hours) { _ in
  685. highlightButtons()
  686. }
  687. .onAppear {
  688. configureView {
  689. highlightButtons()
  690. }
  691. }
  692. .navigationTitle("Home")
  693. .navigationBarHidden(true)
  694. .ignoresSafeArea(.keyboard)
  695. .popup(isPresented: state.isStatusPopupPresented, alignment: .top, direction: .top) {
  696. popup
  697. .padding()
  698. .background(
  699. RoundedRectangle(cornerRadius: 8, style: .continuous)
  700. .fill(colorScheme == .dark ? Color(
  701. "Chart"
  702. ) : Color(UIColor.darkGray))
  703. )
  704. .onTapGesture {
  705. state.isStatusPopupPresented = false
  706. }
  707. .gesture(
  708. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  709. .onEnded { value in
  710. if value.translation.height < 0 {
  711. state.isStatusPopupPresented = false
  712. }
  713. }
  714. )
  715. }
  716. }
  717. @ViewBuilder func tabBar() -> some View {
  718. ZStack(alignment: .bottom) {
  719. TabView {
  720. let carbsRequiredBadge: String? = {
  721. guard let carbsRequired = state.carbsRequired else { return nil }
  722. return carbsRequired > state.settingsManager.settings
  723. .carbsRequiredThreshold ? "\(numberFormatter.string(from: carbsRequired as NSNumber) ?? "") " +
  724. NSLocalizedString("g", comment: "Short representation of grams") : nil
  725. }()
  726. NavigationStack { mainView() }
  727. .tabItem { Label("Main", systemImage: "chart.xyaxis.line") }
  728. .badge(carbsRequiredBadge)
  729. NavigationStack { DataTable.RootView(resolver: resolver) }
  730. .tabItem { Label("History", systemImage: historySFSymbol) }
  731. Spacer()
  732. NavigationStack { OverrideProfilesConfig.RootView(resolver: resolver) }
  733. .tabItem {
  734. Label(
  735. "Profile",
  736. systemImage: "person.fill"
  737. ) }
  738. NavigationStack { Settings.RootView(resolver: resolver) }
  739. .tabItem {
  740. Label(
  741. "Menu",
  742. systemImage: "text.justify"
  743. ) }
  744. }
  745. .tint(Color.tabBar)
  746. Button(
  747. action: {
  748. state.showModal(for: .bolus) },
  749. label: {
  750. Image(systemName: "plus.circle.fill")
  751. .font(.system(size: 40))
  752. .foregroundStyle(Color.tabBar)
  753. .padding(.bottom, 1)
  754. .padding(.horizontal, 20)
  755. }
  756. )
  757. }.ignoresSafeArea(.keyboard, edges: .bottom).blur(radius: state.waitForSuggestion ? 8 : 0)
  758. }
  759. var body: some View {
  760. ZStack(alignment: .center) {
  761. tabBar()
  762. if state.waitForSuggestion {
  763. CustomProgressView(text: "Updating IOB...")
  764. }
  765. }
  766. }
  767. private var popup: some View {
  768. VStack(alignment: .leading, spacing: 4) {
  769. Text(statusTitle).font(.headline).foregroundColor(.white)
  770. .padding(.bottom, 4)
  771. if let determination = determination.first {
  772. TagCloudView(tags: determination.reasonParts).animation(.none, value: false)
  773. Text(determination.reasonConclusion.capitalizingFirstLetter()).font(.caption).foregroundColor(.white)
  774. } else {
  775. Text("No determination found").font(.body).foregroundColor(.white)
  776. }
  777. if let errorMessage = state.errorMessage, let date = state.errorDate {
  778. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  779. .foregroundColor(.white)
  780. .font(.headline)
  781. .padding(.bottom, 4)
  782. .padding(.top, 8)
  783. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  784. } else if let determination = determination.first, (determination.glucose ?? 100) == 400 {
  785. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  786. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  787. }
  788. }
  789. }
  790. private func setStatusTitle() {
  791. guard let determination = determination.first else {
  792. statusTitle = "No Oref determination"
  793. return
  794. }
  795. let dateFormatter = DateFormatter()
  796. dateFormatter.timeStyle = .short
  797. if state.closedLoop
  798. {
  799. statusTitle = NSLocalizedString("Oref Determination enacted at", comment: "Headline in enacted pop up") + " " +
  800. dateFormatter
  801. .string(from: determination.timestamp ?? Date())
  802. } else {
  803. statusTitle = NSLocalizedString("Determinated at", comment: "Headline in suggested pop up") + " " +
  804. dateFormatter
  805. .string(from: determination.deliverAt ?? Date())
  806. }
  807. }
  808. }
  809. }