HomeRootView.swift 38 KB

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