HomeRootView.swift 37 KB

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