HomeRootView.swift 36 KB

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