HomeRootView.swift 38 KB

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