HomeRootView.swift 36 KB

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