HomeRootView.swift 38 KB

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