HomeRootView.swift 42 KB

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