HomeRootView.swift 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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. @ObservedObject var appState = AppState()
  10. @StateObject var state = StateModel()
  11. @State var isStatusPopupPresented = false
  12. @State var showCancelAlert = false
  13. @State var isMenuPresented = false
  14. @State var selectedTab: Int = 0
  15. @State var currentTab: Tab
  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.bgDarkBlue,
  103. Color.bgDarkerDarkBlue,
  104. Color.bgDarkBlue
  105. ]),
  106. startPoint: .top,
  107. endPoint: .bottom
  108. )
  109. :
  110. LinearGradient(
  111. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  112. startPoint: .top,
  113. endPoint: .bottom
  114. )
  115. }
  116. private var historySFSymbol: String {
  117. if #available(iOS 17.0, *) {
  118. return "book.pages"
  119. } else {
  120. return "book"
  121. }
  122. }
  123. var glucoseView: some View {
  124. CurrentGlucoseView(
  125. recentGlucose: $state.recentGlucose,
  126. timerDate: $state.timerDate,
  127. delta: $state.glucoseDelta,
  128. units: $state.units,
  129. alarm: $state.alarm,
  130. lowGlucose: $state.lowGlucose,
  131. highGlucose: $state.highGlucose
  132. ).scaleEffect(0.9)
  133. /*
  134. .onTapGesture {
  135. if state.alarm == nil {
  136. state.openCGM()
  137. } else {
  138. state.showModal(for: .snooze)
  139. }
  140. }
  141. .onLongPressGesture {
  142. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  143. impactHeavy.impactOccurred()
  144. if state.alarm == nil {
  145. state.showModal(for: .snooze)
  146. } else {
  147. state.openCGM()
  148. }
  149. }
  150. */
  151. }
  152. var pumpView: some View {
  153. PumpView(
  154. reservoir: $state.reservoir,
  155. battery: $state.battery,
  156. name: $state.pumpName,
  157. expiresAtDate: $state.pumpExpiresAtDate,
  158. timerDate: $state.timerDate,
  159. timeZone: $state.timeZone,
  160. state: state
  161. )
  162. }
  163. var tempBasalString: String? {
  164. guard let tempRate = state.tempRate else {
  165. return nil
  166. }
  167. let rateString = numberFormatter.string(from: tempRate as NSNumber) ?? "0"
  168. var manualBasalString = ""
  169. if state.apsManager.isManualTempBasal {
  170. manualBasalString = NSLocalizedString(
  171. " - Manual Basal ⚠️",
  172. comment: "Manual Temp basal"
  173. )
  174. }
  175. return rateString + " " + NSLocalizedString(" U/hr", comment: "Unit per hour with space") + manualBasalString
  176. }
  177. var tempTargetString: String? {
  178. guard let tempTarget = state.tempTarget else {
  179. return nil
  180. }
  181. let target = tempTarget.targetBottom ?? 0
  182. let unitString = targetFormatter.string(from: (tempTarget.targetBottom?.asMmolL ?? 0) as NSNumber) ?? ""
  183. let rawString = (tirFormatter.string(from: (tempTarget.targetBottom ?? 0) as NSNumber) ?? "") + " " + state.units
  184. .rawValue
  185. var string = ""
  186. if sliderTTpresets.first?.active ?? false {
  187. let hbt = sliderTTpresets.first?.hbt ?? 0
  188. string = ", " + (tirFormatter.string(from: state.infoPanelTTPercentage(hbt, target) as NSNumber) ?? "") + " %"
  189. }
  190. let percentString = state
  191. .units == .mmolL ? (unitString + " mmol/L" + string) : (rawString + (string == "0" ? "" : string))
  192. return tempTarget.displayName + " " + percentString
  193. }
  194. var overrideString: String? {
  195. guard fetchedPercent.first?.enabled ?? false else {
  196. return nil
  197. }
  198. var percentString = "\((fetchedPercent.first?.percentage ?? 100).formatted(.number)) %"
  199. var target = (fetchedPercent.first?.target ?? 100) as Decimal
  200. let indefinite = (fetchedPercent.first?.indefinite ?? false)
  201. let unit = state.units.rawValue
  202. if state.units == .mmolL {
  203. target = target.asMmolL
  204. }
  205. var targetString = (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " + unit
  206. if tempTargetString != nil || target == 0 { targetString = "" }
  207. percentString = percentString == "100 %" ? "" : percentString
  208. let duration = (fetchedPercent.first?.duration ?? 0) as Decimal
  209. let addedMinutes = Int(duration)
  210. let date = fetchedPercent.first?.date ?? Date()
  211. var newDuration: Decimal = 0
  212. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) > Date() {
  213. newDuration = Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes)
  214. }
  215. var durationString = indefinite ?
  216. "" : newDuration >= 1 ?
  217. (newDuration.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) + " min") :
  218. (
  219. newDuration > 0 ? (
  220. (newDuration * 60).formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) + " s"
  221. ) :
  222. ""
  223. )
  224. let smbToggleString = (fetchedPercent.first?.smbIsOff ?? false) ? " \u{20e0}" : ""
  225. var comma1 = ", "
  226. var comma2 = comma1
  227. var comma3 = comma1
  228. if targetString == "" || percentString == "" { comma1 = "" }
  229. if durationString == "" { comma2 = "" }
  230. if smbToggleString == "" { comma3 = "" }
  231. if percentString == "", targetString == "" {
  232. comma1 = ""
  233. comma2 = ""
  234. }
  235. if percentString == "", targetString == "", smbToggleString == "" {
  236. durationString = ""
  237. comma1 = ""
  238. comma2 = ""
  239. comma3 = ""
  240. }
  241. if durationString == "" {
  242. comma2 = ""
  243. }
  244. if smbToggleString == "" {
  245. comma3 = ""
  246. }
  247. if durationString == "", !indefinite {
  248. return nil
  249. }
  250. return percentString + comma1 + targetString + comma2 + durationString + comma3 + smbToggleString
  251. }
  252. var infoPanel: some View {
  253. HStack(alignment: .center) {
  254. if state.pumpSuspended {
  255. Text("Pump suspended")
  256. .font(.system(size: 15, weight: .bold)).foregroundColor(.loopGray)
  257. .padding(.leading, 8)
  258. } else if let tempBasalString = tempBasalString {
  259. Text(tempBasalString)
  260. .font(.system(size: 15, weight: .bold))
  261. .foregroundColor(.insulin)
  262. .padding(.leading, 8)
  263. }
  264. if state.tins {
  265. Text(
  266. "TINS: \(state.calculateTINS())" +
  267. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  268. )
  269. .font(.system(size: 15, weight: .bold))
  270. .foregroundColor(.insulin)
  271. }
  272. if let tempTargetString = tempTargetString {
  273. Text(tempTargetString)
  274. .font(.caption)
  275. .foregroundColor(.secondary)
  276. }
  277. Spacer()
  278. if state.closedLoop, state.settingsManager.preferences.maxIOB == 0 {
  279. Text("Max IOB: 0").font(.callout).foregroundColor(.orange).padding(.trailing, 20)
  280. }
  281. }
  282. .frame(maxWidth: .infinity, maxHeight: 30)
  283. }
  284. var timeInterval: some View {
  285. HStack(alignment: .center) {
  286. ForEach(timeButtons) { button in
  287. Text(button.active ? NSLocalizedString(button.label, comment: "") : button.number).onTapGesture {
  288. state.hours = button.hours
  289. }
  290. .foregroundStyle(button.active ? (colorScheme == .dark ? Color.white : Color.black).opacity(0.9) : .secondary)
  291. .frame(maxHeight: 30).padding(.horizontal, 8)
  292. .background(
  293. button.active ?
  294. // RGB(30, 60, 95)
  295. (
  296. colorScheme == .dark ? Color(red: 0.1176470588, green: 0.2352941176, blue: 0.3725490196) :
  297. Color.white
  298. ) :
  299. Color
  300. .clear
  301. )
  302. .cornerRadius(20)
  303. }
  304. }
  305. .shadow(
  306. color: Color.black.opacity(colorScheme == .dark ? 0.75 : 0.33),
  307. radius: colorScheme == .dark ? 5 : 3
  308. )
  309. .font(buttonFont)
  310. }
  311. var mainChart: some View {
  312. ZStack {
  313. if state.animatedBackground {
  314. SpriteView(scene: spriteScene, options: [.allowsTransparency])
  315. .ignoresSafeArea()
  316. .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
  317. }
  318. MainChartView(
  319. glucose: $state.glucose,
  320. units: $state.units,
  321. eventualBG: $state.eventualBG,
  322. suggestion: $state.suggestion,
  323. tempBasals: $state.tempBasals,
  324. boluses: $state.boluses,
  325. suspensions: $state.suspensions,
  326. announcement: $state.announcement,
  327. hours: .constant(state.filteredHours),
  328. maxBasal: $state.maxBasal,
  329. autotunedBasalProfile: $state.autotunedBasalProfile,
  330. basalProfile: $state.basalProfile,
  331. tempTargets: $state.tempTargets,
  332. carbs: $state.carbs,
  333. smooth: $state.smooth,
  334. highGlucose: $state.highGlucose,
  335. lowGlucose: $state.lowGlucose,
  336. screenHours: $state.hours,
  337. displayXgridLines: $state.displayXgridLines,
  338. displayYgridLines: $state.displayYgridLines,
  339. thresholdLines: $state.thresholdLines,
  340. isTempTargetActive: $state.isTempTargetActive
  341. )
  342. }
  343. .padding(.bottom)
  344. }
  345. func highlightButtons() {
  346. for i in 0 ..< timeButtons.count {
  347. timeButtons[i].active = timeButtons[i].hours == state.hours
  348. }
  349. }
  350. @ViewBuilder private func bottomPanel(_: GeometryProxy) -> some View {
  351. let colorIcon: Color = (colorScheme == .dark ? Color.white : Color.black).opacity(0.9)
  352. ZStack {
  353. Rectangle()
  354. .fill(Color("Chart"))
  355. .frame(height: UIScreen.main.bounds.height / 13)
  356. .cornerRadius(15)
  357. .shadow(
  358. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) : Color
  359. .black.opacity(0.33),
  360. radius: 3
  361. )
  362. .padding([.leading, .trailing], 10)
  363. HStack {
  364. Button {
  365. state.showModal(for: .dataTable)
  366. }
  367. label: {
  368. if #available(iOS 17.0, *) {
  369. Image(systemName: "book.pages")
  370. .font(.system(size: 24))
  371. .foregroundColor(colorIcon)
  372. .padding(8)
  373. } else {
  374. Image(systemName: "book")
  375. .font(.system(size: 24))
  376. .foregroundColor(colorIcon)
  377. .padding(8)
  378. }
  379. }
  380. .foregroundColor(colorIcon)
  381. .buttonStyle(.borderless)
  382. Spacer()
  383. Button { state.showModal(for: .addCarbs(editMode: false, override: false)) }
  384. label: {
  385. ZStack(alignment: Alignment(horizontal: .trailing, vertical: .bottom)) {
  386. Image(systemName: "fork.knife")
  387. .font(.system(size: 24))
  388. .foregroundColor(colorIcon)
  389. .padding(8)
  390. if let carbsReq = state.carbsRequired {
  391. Text(numberFormatter.string(from: carbsReq as NSNumber)!)
  392. .font(.caption)
  393. .foregroundColor(.white)
  394. .padding(4)
  395. .background(Capsule().fill(Color.red))
  396. }
  397. }
  398. }.buttonStyle(.borderless)
  399. Spacer()
  400. // Button { state.showModal(for: .addTempTarget) }
  401. // label: {
  402. // Image(systemName: "target")
  403. // .font(.system(size: 24))
  404. // .padding(8)
  405. // }
  406. // .foregroundColor(state.isTempTargetActive ? Color.purple : colorIcon)
  407. // .buttonStyle(.borderless)
  408. // Spacer()
  409. Button {
  410. state.showModal(for: .bolus(
  411. waitForSuggestion: true,
  412. fetch: false
  413. ))
  414. }
  415. label: {
  416. Image(systemName: "syringe.fill")
  417. .font(.system(size: 24))
  418. .foregroundColor(colorIcon)
  419. .padding(8)
  420. }
  421. .foregroundColor(colorIcon)
  422. .buttonStyle(.borderless)
  423. Spacer()
  424. if state.allowManualTemp {
  425. Button { state.showModal(for: .manualTempBasal) }
  426. label: {
  427. Image("bolus1")
  428. .renderingMode(.template)
  429. .resizable()
  430. .frame(width: 24, height: 24)
  431. .padding(8)
  432. }
  433. .foregroundColor(colorIcon)
  434. .buttonStyle(.borderless)
  435. Spacer()
  436. }
  437. Button {
  438. state.showModal(for: .overrideProfilesConfig)
  439. } label: {
  440. Image(systemName: state.isTempTargetActive || overrideString != nil ? "person.fill" : "person")
  441. .font(.system(size: 26))
  442. .padding(8)
  443. }
  444. .foregroundColor((state.isTempTargetActive || (overrideString != nil)) ? Color.purple : colorIcon)
  445. .buttonStyle(.borderless)
  446. Spacer()
  447. Button {
  448. isMenuPresented.toggle()
  449. } label: {
  450. Image(systemName: "text.justify")
  451. .font(.system(size: 26))
  452. .padding(8)
  453. }
  454. .foregroundColor((state.isTempTargetActive || (overrideString != nil)) ? Color.purple : colorIcon)
  455. .buttonStyle(.borderless)
  456. }
  457. .padding(.horizontal, 24)
  458. .padding(.bottom, 16)
  459. }
  460. }
  461. @ViewBuilder func bolusProgressBar(_ progress: Decimal) -> some View {
  462. GeometryReader { geo in
  463. Rectangle()
  464. .frame(height: 6)
  465. .foregroundColor(.clear)
  466. .background(
  467. LinearGradient(colors: [
  468. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  469. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  470. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  471. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  472. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  473. ], startPoint: .leading, endPoint: .trailing)
  474. .mask(alignment: .leading) {
  475. Rectangle()
  476. .frame(width: geo.size.width * CGFloat(progress))
  477. }
  478. )
  479. }
  480. }
  481. @ViewBuilder func bolusProgressView(_: GeometryProxy, _ progress: Decimal) -> some View {
  482. let colorRectangle: Color = colorScheme == .dark ? Color(
  483. "Chart"
  484. ) : Color.white
  485. let colorIcon = (colorScheme == .dark ? Color.white : Color.black).opacity(0.9)
  486. let bolusTotal = state.boluses.last?.amount ?? 0
  487. let bolusFraction = progress * bolusTotal
  488. let bolusString =
  489. (bolusProgressFormatter.string(from: bolusFraction as NSNumber) ?? "0")
  490. + " of " +
  491. (numberFormatter.string(from: bolusTotal as NSNumber) ?? "0")
  492. + NSLocalizedString(" U", comment: "Insulin unit")
  493. ZStack(alignment: .bottom) {
  494. HStack {
  495. Button {
  496. state.cancelBolus()
  497. } label: {
  498. HStack(alignment: .center) {
  499. Text("Bolusing")
  500. .font(.subheadline)
  501. .fontWeight(.bold)
  502. Text(bolusString)
  503. .font(.subheadline)
  504. Spacer()
  505. Image(systemName: "xmark.app")
  506. .font(.system(size: 30))
  507. .padding(1)
  508. }
  509. }.foregroundColor(colorIcon)
  510. }.padding()
  511. bolusProgressBar(progress).offset(y: 59)
  512. }
  513. .background(colorRectangle)
  514. .clipShape(RoundedRectangle(cornerRadius: 8))
  515. .shadow(
  516. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  517. Color.black.opacity(0.33),
  518. radius: 3
  519. )
  520. .frame(height: 62, alignment: .center)
  521. .padding(.horizontal, 10)
  522. .offset(y: -90)
  523. }
  524. @ViewBuilder func rightHeaderPanel(_: GeometryProxy) -> some View {
  525. VStack(alignment: .leading, spacing: 20) {
  526. /// Loop view at bottomLeading
  527. LoopView(
  528. suggestion: $state.suggestion,
  529. enactedSuggestion: $state.enactedSuggestion,
  530. closedLoop: $state.closedLoop,
  531. timerDate: $state.timerDate,
  532. isLooping: $state.isLooping,
  533. lastLoopDate: $state.lastLoopDate,
  534. manualTempBasal: $state.manualTempBasal
  535. ).onTapGesture {
  536. state.isStatusPopupPresented = true
  537. }.onLongPressGesture {
  538. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  539. impactHeavy.impactOccurred()
  540. state.runLoop()
  541. }
  542. /// eventualBG string at bottomTrailing
  543. if let eventualBG = state.eventualBG {
  544. HStack {
  545. Image(systemName: "arrow.right.circle")
  546. .font(.system(size: 16, weight: .bold))
  547. Text(
  548. numberFormatter.string(
  549. from: (
  550. state.units == .mmolL ? eventualBG
  551. .asMmolL : Decimal(eventualBG)
  552. ) as NSNumber
  553. )!
  554. )
  555. .font(.system(size: 16))
  556. }
  557. }
  558. }
  559. }
  560. @ViewBuilder func mealPanel(_: GeometryProxy) -> some View {
  561. HStack {
  562. HStack {
  563. Image(systemName: "syringe.fill")
  564. .font(.system(size: 16))
  565. .foregroundColor(Color.insulin)
  566. Text(
  567. (numberFormatter.string(from: (state.suggestion?.iob ?? 0) as NSNumber) ?? "0") +
  568. NSLocalizedString(" U", comment: "Insulin unit")
  569. )
  570. .font(.system(size: 16, weight: .bold))
  571. }
  572. Spacer()
  573. HStack {
  574. Image(systemName: "fork.knife")
  575. .font(.system(size: 16))
  576. .foregroundColor(.loopYellow)
  577. Text(
  578. (numberFormatter.string(from: (state.suggestion?.cob ?? 0) as NSNumber) ?? "0") +
  579. NSLocalizedString(" g", comment: "gram of carbs")
  580. )
  581. .font(.system(size: 16, weight: .bold))
  582. }
  583. Spacer()
  584. HStack {
  585. if state.pumpSuspended {
  586. Text("Pump suspended")
  587. .font(.system(size: 12, weight: .bold)).foregroundColor(.loopGray)
  588. } else if let tempBasalString = tempBasalString {
  589. Image(systemName: "drop.circle")
  590. .font(.system(size: 16))
  591. .foregroundColor(.insulinTintColor)
  592. Text(tempBasalString)
  593. .font(.system(size: 16, weight: .bold))
  594. }
  595. }
  596. if !state.tins {
  597. Spacer()
  598. Text(
  599. "TDD: " + (numberFormatter.string(from: (state.suggestion?.tdd ?? 0) as NSNumber) ?? "0") +
  600. NSLocalizedString(" U", comment: "Insulin unit")
  601. )
  602. .font(.system(size: 16, weight: .bold))
  603. } else {
  604. Spacer()
  605. HStack {
  606. Text(
  607. "TINS: \(state.roundedTotalBolus)" +
  608. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  609. )
  610. .font(.system(size: 16, weight: .bold))
  611. .onChange(of: state.hours) { _ in
  612. state.roundedTotalBolus = state.calculateTINS()
  613. }
  614. .onAppear {
  615. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  616. state.roundedTotalBolus = state.calculateTINS()
  617. }
  618. }
  619. }
  620. }
  621. }.padding(.horizontal, 10)
  622. }
  623. @ViewBuilder func profileView(_: GeometryProxy) -> some View {
  624. let colourChart: Color = colorScheme == .dark ? Color(
  625. "Chart"
  626. ) : .white
  627. if let overrideString = overrideString {
  628. ZStack {
  629. /// rectangle as background
  630. RoundedRectangle(cornerRadius: 15)
  631. .fill(colourChart)
  632. .clipShape(RoundedRectangle(cornerRadius: 15))
  633. .frame(height: UIScreen.main.bounds.height / 20)
  634. .shadow(
  635. color:
  636. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  637. radius: 1
  638. )
  639. HStack {
  640. /// actual profile view
  641. Image(systemName: "person.fill")
  642. .font(.system(size: 20))
  643. .foregroundStyle(Color.purple)
  644. Spacer()
  645. Text(overrideString)
  646. .font(.system(size: 18))
  647. Spacer()
  648. Image(systemName: "xmark.app")
  649. .font(.system(size: 20))
  650. }.padding(.horizontal, 10)
  651. .alert(
  652. "Return to Normal?", isPresented: $showCancelAlert,
  653. actions: {
  654. Button("No", role: .cancel) {}
  655. Button("Yes", role: .destructive) {
  656. state.cancelProfile()
  657. }
  658. }, message: { Text("This will change settings back to your normal profile.") }
  659. )
  660. .padding(.trailing, 8)
  661. .onTapGesture {
  662. showCancelAlert = true
  663. }
  664. }.padding(.horizontal, 10)
  665. }
  666. /// just show temp target if no profile is already active
  667. if overrideString == nil, let tempTargetString = tempTargetString {
  668. ZStack {
  669. /// rectangle as background
  670. RoundedRectangle(cornerRadius: 15)
  671. .fill(colourChart)
  672. .clipShape(RoundedRectangle(cornerRadius: 15))
  673. .frame(height: UIScreen.main.bounds.height / 20)
  674. .shadow(
  675. color:
  676. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  677. radius: 1
  678. )
  679. HStack {
  680. Image(systemName: "person.fill")
  681. .font(.system(size: 20))
  682. .foregroundStyle(Color.purple)
  683. Spacer()
  684. Text(tempTargetString)
  685. .font(.system(size: 15))
  686. Spacer()
  687. }.padding(.horizontal, 10)
  688. }.padding(.horizontal, 10)
  689. }
  690. }
  691. @ViewBuilder func menuSymbols(action: @escaping () -> Void, systemName: String) -> some View {
  692. Button(
  693. action: action,
  694. label: {
  695. HStack {
  696. Image(systemName: systemName)
  697. .font(.system(size: 21))
  698. .foregroundStyle(colorScheme == .dark ? .white : .black)
  699. }.padding(.top, 1)
  700. }
  701. )
  702. }
  703. @ViewBuilder func menuElements(action: @escaping () -> Void, title: String) -> some View {
  704. Button(
  705. action: action,
  706. label: {
  707. HStack {
  708. Text(title)
  709. .font(.system(size: 19))
  710. .foregroundStyle(colorScheme == .dark ? .white : .black)
  711. Spacer()
  712. Image(systemName: "arrow.right")
  713. .font(.system(size: 21))
  714. .foregroundStyle(colorScheme == .dark ? .white : .black)
  715. }.padding(.top, 1)
  716. }
  717. )
  718. }
  719. @ViewBuilder func sideMenuView() -> some View {
  720. ZStack {
  721. RoundedRectangle(cornerRadius: 8)
  722. .fill(color)
  723. .shadow(
  724. color: Color.black.opacity(0.33),
  725. radius: 3
  726. )
  727. .ignoresSafeArea(edges: .all)
  728. VStack(alignment: .leading) {
  729. Button {
  730. isMenuPresented.toggle()
  731. } label: {
  732. HStack {
  733. Image(systemName: "arrow.left")
  734. .font(.system(size: 30))
  735. .foregroundStyle(colorScheme == .dark ? .white : .black)
  736. Text("Menu")
  737. .font(.system(size: 30)).fontWeight(.bold)
  738. .foregroundStyle(colorScheme == .dark ? .white : .black)
  739. }
  740. }
  741. .padding(.top, 60)
  742. HStack(spacing: 15) {
  743. VStack(alignment: .leading, spacing: 25, content: {
  744. menuSymbols(action: { state.showModal(for: .statistics) }, systemName: "chart.bar.xaxis")
  745. .padding(.top, 20)
  746. menuSymbols(action: {
  747. if state.pumpDisplayState != nil {
  748. state.setupPump = true
  749. }
  750. }, systemName: "cross.vial.fill")
  751. menuSymbols(action: {
  752. if state.alarm == nil {
  753. state.openCGM()
  754. } else {
  755. state.showModal(for: .snooze)
  756. }
  757. }, systemName: "sensor.tag.radiowaves.forward.fill")
  758. menuSymbols(action: { state.showModal(for: .addTempTarget) }, systemName: "target")
  759. menuSymbols(action: { state.showModal(for: .settings) }, systemName: "gear")
  760. Spacer()
  761. })
  762. VStack(alignment: .leading, spacing: 25, content: {
  763. menuElements(action: { state.showModal(for: .statistics) }, title: "Statistics")
  764. .padding(.top, 20)
  765. menuElements(action: {
  766. if state.pumpDisplayState != nil {
  767. state.setupPump = true
  768. }
  769. }, title: "Pump Settings")
  770. menuElements(action: {
  771. if state.alarm == nil {
  772. state.openCGM()
  773. } else {
  774. state.showModal(for: .snooze)
  775. }
  776. }, title: "CGM")
  777. menuElements(action: { state.showModal(for: .addTempTarget) }, title: "Temp targets")
  778. menuElements(action: { state.showModal(for: .settings) }, title: "Settings")
  779. Spacer()
  780. })
  781. }
  782. }.padding(.horizontal, 25)
  783. }
  784. .frame(width: UIScreen.main.bounds.width / 1.2, height: UIScreen.main.bounds.height - 20)
  785. }
  786. @ViewBuilder func mainView() -> some View {
  787. GeometryReader { geo in
  788. ZStack(alignment: .trailing) {
  789. VStack(spacing: 0) {
  790. ZStack {
  791. /// glucose bobble
  792. glucoseView
  793. /// right panel with loop status and evBG
  794. HStack {
  795. Spacer()
  796. rightHeaderPanel(geo)
  797. }.padding(.trailing, 20)
  798. /// left panel with pump related info
  799. HStack {
  800. pumpView
  801. Spacer()
  802. }.padding(.leading, 20)
  803. HStack {
  804. Spacer()
  805. Button {
  806. isMenuPresented.toggle()
  807. }
  808. label: {
  809. Image(systemName: "text.justify")
  810. .font(.body).foregroundStyle(colorScheme == .dark ? Color.white : Color.black)
  811. }.padding(.trailing, 20).padding(.bottom, 110)
  812. }
  813. }.padding(.top, 70)
  814. mealPanel(geo).padding(.vertical, 25)
  815. profileView(geo).padding(.vertical)
  816. RoundedRectangle(cornerRadius: 15)
  817. .fill(Color.chart)
  818. .overlay(mainChart)
  819. .clipShape(RoundedRectangle(cornerRadius: 15))
  820. .shadow(
  821. color: colorScheme == .dark ? Color(
  822. red: 0.02745098039,
  823. green: 0.1098039216,
  824. blue: 0.1411764706
  825. ) :
  826. Color.black.opacity(0.33),
  827. radius: 3
  828. )
  829. .padding(.horizontal, 10)
  830. .frame(maxHeight: UIScreen.main.bounds.height / 2.1)
  831. timeInterval.padding(.top, 25)
  832. Spacer()
  833. ZStack(alignment: .bottom) {
  834. // bottomPanel(geo)
  835. if let progress = state.bolusProgress {
  836. bolusProgressView(geo, progress)
  837. }
  838. }
  839. }
  840. // tabbar
  841. }
  842. .background(color)
  843. .blur(radius: isMenuPresented ? 5 : 0)
  844. .edgesIgnoringSafeArea(.all)
  845. }
  846. .onChange(of: state.hours) { _ in
  847. highlightButtons()
  848. }
  849. .onAppear {
  850. configureView {
  851. highlightButtons()
  852. }
  853. }
  854. .navigationTitle("Home")
  855. .navigationBarHidden(true)
  856. .ignoresSafeArea(.keyboard)
  857. .popup(isPresented: state.isStatusPopupPresented, alignment: .top, direction: .top) {
  858. popup
  859. .padding()
  860. .background(
  861. RoundedRectangle(cornerRadius: 8, style: .continuous)
  862. .fill(colorScheme == .dark ? Color(
  863. "Chart"
  864. ) : Color(UIColor.darkGray))
  865. )
  866. .onTapGesture {
  867. state.isStatusPopupPresented = false
  868. }
  869. .gesture(
  870. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  871. .onEnded { value in
  872. if value.translation.height < 0 {
  873. state.isStatusPopupPresented = false
  874. }
  875. }
  876. )
  877. }
  878. }
  879. @ViewBuilder func tabBar() -> some View {
  880. TabView(selection: $appState.currentTab) {
  881. mainView()
  882. .tabItem { Label("Home", systemImage: "house") }
  883. .tag(Tab.home)
  884. NavigationStack { DataTable.RootView(resolver: resolver) }
  885. .tabItem { Label("History", systemImage: historySFSymbol) }
  886. .tag(Tab.history)
  887. NavigationStack { AddCarbs.RootView(resolver: resolver, editMode: false, override: false) }
  888. .tabItem { Label("Carbs", systemImage: "fork.knife") }
  889. .tag(Tab.carbs)
  890. NavigationStack { Bolus.RootView(resolver: resolver, waitForSuggestion: false, fetch: false, appState: appState)
  891. }
  892. .tabItem { Label("Bolus", systemImage: "syringe.fill") }
  893. .tag(Tab.bolus)
  894. NavigationStack { OverrideProfilesConfig.RootView(resolver: resolver) }
  895. .tabItem {
  896. Label(
  897. "Profile",
  898. systemImage: state.isTempTargetActive || overrideString != nil ? "person.fill" : "person"
  899. ) }
  900. .tag(Tab.profile)
  901. }.tint(Color.tabBar)
  902. }
  903. var body: some View {
  904. ZStack(alignment: .trailing) {
  905. tabBar()
  906. // burger menu
  907. if isMenuPresented {
  908. HStack {
  909. sideMenuView().background(Color.chart).ignoresSafeArea(.all)
  910. }
  911. }
  912. }
  913. }
  914. private var popup: some View {
  915. VStack(alignment: .leading, spacing: 4) {
  916. Text(state.statusTitle).font(.headline).foregroundColor(.white)
  917. .padding(.bottom, 4)
  918. if let suggestion = state.suggestion {
  919. TagCloudView(tags: suggestion.reasonParts).animation(.none, value: false)
  920. Text(suggestion.reasonConclusion.capitalizingFirstLetter()).font(.caption).foregroundColor(.white)
  921. } else {
  922. Text("No sugestion found").font(.body).foregroundColor(.white)
  923. }
  924. if let errorMessage = state.errorMessage, let date = state.errorDate {
  925. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  926. .foregroundColor(.white)
  927. .font(.headline)
  928. .padding(.bottom, 4)
  929. .padding(.top, 8)
  930. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  931. } else if let suggestion = state.suggestion, (suggestion.bg ?? 100) == 400 {
  932. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  933. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  934. }
  935. }
  936. }
  937. }
  938. }
  939. class AppState: ObservableObject {
  940. @Published var currentTab: Tab = .home
  941. }
  942. enum Tab {
  943. case home
  944. case history
  945. case carbs
  946. case bolus
  947. case profile
  948. }