HomeRootView.swift 39 KB

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