HomeRootView.swift 39 KB

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