HomeRootView.swift 38 KB

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