HomeRootView.swift 38 KB

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