HomeRootView.swift 40 KB

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