HomeRootView.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  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: $state.mostRecentDetermination,
  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 = state.determinationsFromCoreData.first?.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: (state.mostRecentDetermination?.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: (state.mostRecentDetermination?.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: " +
  488. (
  489. numberFormatter
  490. .string(from: (state.mostRecentDetermination?.totalDailyDose ?? 0) as NSNumber) ?? "0"
  491. ) +
  492. NSLocalizedString(" U", comment: "Insulin unit")
  493. )
  494. .font(.system(size: 16, weight: .bold, design: .rounded))
  495. } else {
  496. Spacer()
  497. HStack {
  498. Text(
  499. "TINS: \(state.roundedTotalBolus)" +
  500. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  501. )
  502. .font(.system(size: 16, weight: .bold, design: .rounded))
  503. .onChange(of: state.hours) { _ in
  504. state.roundedTotalBolus = state.calculateTINS()
  505. }
  506. .onAppear {
  507. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  508. state.roundedTotalBolus = state.calculateTINS()
  509. }
  510. }
  511. }
  512. }
  513. }.padding(.horizontal, 10)
  514. }
  515. @ViewBuilder func profileView(_: GeometryProxy) -> some View {
  516. ZStack {
  517. /// rectangle as background
  518. RoundedRectangle(cornerRadius: 15)
  519. .fill(
  520. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color.insulin
  521. .opacity(0.1)
  522. )
  523. .clipShape(RoundedRectangle(cornerRadius: 15))
  524. .frame(height: UIScreen.main.bounds.height / 18)
  525. .shadow(
  526. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  527. Color.black.opacity(0.33),
  528. radius: 3
  529. )
  530. HStack {
  531. /// actual profile view
  532. Image(systemName: "person.fill")
  533. .font(.system(size: 25))
  534. Spacer()
  535. if let overrideString = overrideString {
  536. VStack {
  537. Text(selectedProfile().name)
  538. .font(.subheadline)
  539. .frame(maxWidth: .infinity, alignment: .leading)
  540. Text(overrideString)
  541. .font(.caption)
  542. .frame(maxWidth: .infinity, alignment: .leading)
  543. }.padding(.leading, 5)
  544. Spacer()
  545. Image(systemName: "xmark.app")
  546. .font(.system(size: 25))
  547. } else {
  548. if tempTargetString == nil {
  549. VStack {
  550. Text(selectedProfile().name)
  551. .font(.subheadline)
  552. .frame(maxWidth: .infinity, alignment: .leading)
  553. Text("100 %")
  554. .font(.caption)
  555. .frame(maxWidth: .infinity, alignment: .leading)
  556. }.padding(.leading, 5)
  557. Spacer()
  558. /// to ensure the same position....
  559. Image(systemName: "xmark.app")
  560. .font(.system(size: 25))
  561. .foregroundStyle(Color.clear)
  562. }
  563. }
  564. }.padding(.horizontal, 10)
  565. .alert(
  566. "Return to Normal?", isPresented: $showCancelAlert,
  567. actions: {
  568. Button("No", role: .cancel) {}
  569. Button("Yes", role: .destructive) {
  570. state.cancelProfile()
  571. }
  572. }, message: { Text("This will change settings back to your normal profile.") }
  573. )
  574. .padding(.trailing, 8)
  575. .onTapGesture {
  576. if selectedProfile().name != "Normal Profile" {
  577. showCancelAlert = true
  578. }
  579. }
  580. }.padding(.horizontal, 10).padding(.bottom, 10)
  581. .overlay {
  582. /// just show temp target if no profile is already active
  583. if overrideString == nil, let tempTargetString = tempTargetString {
  584. ZStack {
  585. /// rectangle as background
  586. RoundedRectangle(cornerRadius: 15)
  587. .fill(
  588. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) :
  589. Color
  590. .insulin
  591. .opacity(0.2)
  592. )
  593. .clipShape(RoundedRectangle(cornerRadius: 15))
  594. .frame(height: UIScreen.main.bounds.height / 18)
  595. .shadow(
  596. color: colorScheme == .dark ? Color(
  597. red: 0.02745098039,
  598. green: 0.1098039216,
  599. blue: 0.1411764706
  600. ) :
  601. Color.black.opacity(0.33),
  602. radius: 3
  603. )
  604. HStack {
  605. Image(systemName: "person.fill")
  606. .font(.system(size: 25))
  607. Spacer()
  608. Text(tempTargetString)
  609. .font(.subheadline)
  610. Spacer()
  611. }.padding(.horizontal, 10)
  612. }.padding(.horizontal, 10).padding(.bottom, 10)
  613. }
  614. }
  615. }
  616. @ViewBuilder func bolusProgressBar(_ progress: Decimal) -> some View {
  617. GeometryReader { geo in
  618. RoundedRectangle(cornerRadius: 15)
  619. .frame(height: 6)
  620. .foregroundColor(.clear)
  621. .background(
  622. LinearGradient(colors: [
  623. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  624. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  625. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  626. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  627. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  628. ], startPoint: .leading, endPoint: .trailing)
  629. .mask(alignment: .leading) {
  630. RoundedRectangle(cornerRadius: 15)
  631. .frame(width: geo.size.width * CGFloat(progress))
  632. }
  633. )
  634. }
  635. }
  636. @ViewBuilder func bolusView(_: GeometryProxy, _ progress: Decimal) -> some View {
  637. let bolusTotal = state.boluses.last?.amount ?? 0
  638. let bolusFraction = progress * bolusTotal
  639. let bolusString =
  640. (bolusProgressFormatter.string(from: bolusFraction as NSNumber) ?? "0")
  641. + " of " +
  642. (numberFormatter.string(from: bolusTotal as NSNumber) ?? "0")
  643. + NSLocalizedString(" U", comment: "Insulin unit")
  644. ZStack {
  645. /// rectangle as background
  646. RoundedRectangle(cornerRadius: 15)
  647. .fill(
  648. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color.insulin
  649. .opacity(0.2)
  650. )
  651. .clipShape(RoundedRectangle(cornerRadius: 15))
  652. .frame(height: UIScreen.main.bounds.height / 18)
  653. .shadow(
  654. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  655. Color.black.opacity(0.33),
  656. radius: 3
  657. )
  658. /// actual bolus view
  659. HStack {
  660. Image(systemName: "cross.vial.fill")
  661. .font(.system(size: 25))
  662. Spacer()
  663. VStack {
  664. Text("Bolusing")
  665. .font(.subheadline)
  666. .frame(maxWidth: .infinity, alignment: .leading)
  667. Text(bolusString)
  668. .font(.caption)
  669. .frame(maxWidth: .infinity, alignment: .leading)
  670. }.padding(.leading, 5)
  671. Spacer()
  672. Button {
  673. state.waitForSuggestion = true
  674. state.cancelBolus()
  675. } label: {
  676. Image(systemName: "xmark.app")
  677. .font(.system(size: 25))
  678. }
  679. }.padding(.horizontal, 10)
  680. .padding(.trailing, 8)
  681. }.padding(.horizontal, 10).padding(.bottom, 10)
  682. .overlay(alignment: .bottom) {
  683. bolusProgressBar(progress).padding(.horizontal, 18).offset(y: 45)
  684. }.clipShape(RoundedRectangle(cornerRadius: 15))
  685. }
  686. @ViewBuilder func mainView() -> some View {
  687. GeometryReader { geo in
  688. VStack(spacing: 0) {
  689. // Spacer()
  690. // .frame(height: UIScreen.main.bounds.height / 40)
  691. ZStack {
  692. /// glucose bobble
  693. glucoseView
  694. /// right panel with loop status and evBG
  695. HStack {
  696. Spacer()
  697. rightHeaderPanel(geo)
  698. }.padding(.trailing, 20)
  699. /// left panel with pump related info
  700. HStack {
  701. pumpView
  702. Spacer()
  703. }.padding(.leading, 20)
  704. }.padding(.top, 10)
  705. mealPanel(geo).padding(.top, 30).padding(.bottom, 20)
  706. mainChart
  707. timeInterval.padding(.top, 20).padding(.bottom, 40)
  708. if let progress = state.bolusProgress {
  709. bolusView(geo, progress).padding(.bottom, 10)
  710. } else {
  711. profileView(geo).padding(.bottom, 10)
  712. }
  713. }
  714. .background(color)
  715. }
  716. .onChange(of: state.hours) { _ in
  717. highlightButtons()
  718. }
  719. .onAppear {
  720. configureView {
  721. highlightButtons()
  722. }
  723. }
  724. .navigationTitle("Home")
  725. .navigationBarHidden(true)
  726. .ignoresSafeArea(.keyboard)
  727. .popup(isPresented: state.isStatusPopupPresented, alignment: .top, direction: .top) {
  728. popup
  729. .padding()
  730. .background(
  731. RoundedRectangle(cornerRadius: 8, style: .continuous)
  732. .fill(colorScheme == .dark ? Color(
  733. "Chart"
  734. ) : Color(UIColor.darkGray))
  735. )
  736. .onTapGesture {
  737. state.isStatusPopupPresented = false
  738. }
  739. .gesture(
  740. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  741. .onEnded { value in
  742. if value.translation.height < 0 {
  743. state.isStatusPopupPresented = false
  744. }
  745. }
  746. )
  747. }
  748. }
  749. @ViewBuilder func tabBar() -> some View {
  750. ZStack(alignment: .bottom) {
  751. TabView {
  752. let carbsRequiredBadge: String? = {
  753. guard let carbsRequired = state.mostRecentDetermination?.carbsRequired as? Decimal else { return nil }
  754. if carbsRequired > state.settingsManager.settings.carbsRequiredThreshold {
  755. let numberAsNSNumber = NSDecimalNumber(decimal: carbsRequired)
  756. let formattedNumber = numberFormatter.string(from: numberAsNSNumber) ?? ""
  757. return formattedNumber + " g"
  758. } else {
  759. return nil
  760. }
  761. }()
  762. NavigationStack { mainView() }
  763. .tabItem { Label("Main", systemImage: "chart.xyaxis.line") }
  764. .badge(carbsRequiredBadge)
  765. NavigationStack { DataTable.RootView(resolver: resolver) }
  766. .tabItem { Label("History", systemImage: historySFSymbol) }
  767. Spacer()
  768. NavigationStack { OverrideProfilesConfig.RootView(resolver: resolver) }
  769. .tabItem {
  770. Label(
  771. "Profile",
  772. systemImage: "person.fill"
  773. ) }
  774. NavigationStack { Settings.RootView(resolver: resolver) }
  775. .tabItem {
  776. Label(
  777. "Menu",
  778. systemImage: "text.justify"
  779. ) }
  780. }
  781. .tint(Color.tabBar)
  782. Button(
  783. action: {
  784. state.showModal(for: .bolus) },
  785. label: {
  786. Image(systemName: "plus.circle.fill")
  787. .font(.system(size: 40))
  788. .foregroundStyle(Color.tabBar)
  789. .padding(.bottom, 1)
  790. .padding(.horizontal, 20)
  791. }
  792. )
  793. }.ignoresSafeArea(.keyboard, edges: .bottom).blur(radius: state.waitForSuggestion ? 8 : 0)
  794. }
  795. var body: some View {
  796. ZStack(alignment: .center) {
  797. tabBar()
  798. if state.waitForSuggestion {
  799. CustomProgressView(text: "Updating IOB...")
  800. }
  801. }
  802. }
  803. private var popup: some View {
  804. VStack(alignment: .leading, spacing: 4) {
  805. Text(statusTitle).font(.headline).foregroundColor(.white)
  806. .padding(.bottom, 4)
  807. if let determination = state.determinationsFromCoreData.first {
  808. if determination.glucose == 400 {
  809. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  810. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  811. } else {
  812. TagCloudView(tags: determination.reasonParts).animation(.none, value: false)
  813. Text(determination.reasonConclusion.capitalizingFirstLetter()).font(.caption).foregroundColor(.white)
  814. }
  815. } else {
  816. Text("No determination found").font(.body).foregroundColor(.white)
  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 determination = state.determinationsFromCoreData.first {
  830. let dateFormatter = DateFormatter()
  831. dateFormatter.timeStyle = .short
  832. statusTitle = NSLocalizedString("Oref Determination enacted at", comment: "Headline in enacted pop up") +
  833. " " +
  834. dateFormatter
  835. .string(from: determination.deliverAt ?? Date())
  836. } else {
  837. statusTitle = "No Oref determination"
  838. return
  839. }
  840. }
  841. }
  842. }