HomeRootView.swift 36 KB

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