HomeRootView.swift 38 KB

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