HomeRootView.swift 39 KB

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