HomeRootView.swift 37 KB

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