HomeRootView.swift 39 KB

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