HomeRootView.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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. @Environment(\.managedObjectContext) var moc
  13. @Environment(\.colorScheme) var colorScheme
  14. @FetchRequest(
  15. entity: Override.entity(),
  16. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  17. ) var fetchedPercent: FetchedResults<Override>
  18. @FetchRequest(
  19. entity: OverridePresets.entity(),
  20. sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)], predicate: NSPredicate(
  21. format: "name != %@", "" as String
  22. )
  23. ) var fetchedProfiles: FetchedResults<OverridePresets>
  24. @FetchRequest(
  25. entity: TempTargets.entity(),
  26. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  27. ) var sliderTTpresets: FetchedResults<TempTargets>
  28. @FetchRequest(
  29. entity: TempTargetsSlider.entity(),
  30. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  31. ) var enactedSliderTT: FetchedResults<TempTargetsSlider>
  32. // MARK: FOR PICKER TO SCALE X AXIS GRAPH
  33. enum Scale: String, CaseIterable, Identifiable {
  34. case one
  35. case three
  36. case six
  37. case twelve
  38. case twentyfour
  39. var id: Self { self }
  40. }
  41. @State private var scale: Scale = .three
  42. // @State var screenHours: Int
  43. private var numberFormatter: NumberFormatter {
  44. let formatter = NumberFormatter()
  45. formatter.numberStyle = .decimal
  46. formatter.maximumFractionDigits = 2
  47. return formatter
  48. }
  49. private var fetchedTargetFormatter: NumberFormatter {
  50. let formatter = NumberFormatter()
  51. formatter.numberStyle = .decimal
  52. if state.units == .mmolL {
  53. formatter.maximumFractionDigits = 1
  54. } else { formatter.maximumFractionDigits = 0 }
  55. return formatter
  56. }
  57. private var targetFormatter: NumberFormatter {
  58. let formatter = NumberFormatter()
  59. formatter.numberStyle = .decimal
  60. formatter.maximumFractionDigits = 1
  61. return formatter
  62. }
  63. private var tirFormatter: NumberFormatter {
  64. let formatter = NumberFormatter()
  65. formatter.numberStyle = .decimal
  66. formatter.maximumFractionDigits = 0
  67. return formatter
  68. }
  69. private var dateFormatter: DateFormatter {
  70. let dateFormatter = DateFormatter()
  71. dateFormatter.timeStyle = .short
  72. return dateFormatter
  73. }
  74. private var spriteScene: SKScene {
  75. let scene = SnowScene()
  76. scene.scaleMode = .resizeFill
  77. scene.backgroundColor = .clear
  78. return scene
  79. }
  80. @ViewBuilder func header(_ geo: GeometryProxy) -> some View {
  81. HStack(alignment: .bottom) {
  82. Spacer()
  83. cobIobView
  84. Spacer()
  85. glucoseView
  86. Spacer()
  87. pumpView
  88. Spacer()
  89. loopView
  90. Spacer()
  91. }
  92. .frame(maxWidth: .infinity)
  93. .padding(.top, 10 + geo.safeAreaInsets.top)
  94. .padding(.bottom, 10)
  95. .background(Color.gray.opacity(0.3))
  96. }
  97. var cobIobView: some View {
  98. VStack(alignment: .leading, spacing: 12) {
  99. HStack {
  100. Text("IOB").font(.footnote).foregroundColor(.secondary)
  101. Text(
  102. (numberFormatter.string(from: (state.suggestion?.iob ?? 0) as NSNumber) ?? "0") +
  103. NSLocalizedString(" U", comment: "Insulin unit")
  104. )
  105. .font(.footnote).fontWeight(.bold)
  106. }.frame(alignment: .top)
  107. HStack {
  108. Text("COB").font(.footnote).foregroundColor(.secondary)
  109. Text(
  110. (numberFormatter.string(from: (state.suggestion?.cob ?? 0) as NSNumber) ?? "0") +
  111. NSLocalizedString(" g", comment: "gram of carbs")
  112. )
  113. .font(.footnote).fontWeight(.bold)
  114. }.frame(alignment: .bottom)
  115. }
  116. }
  117. var glucoseView: some View {
  118. CurrentGlucoseView(
  119. recentGlucose: $state.recentGlucose,
  120. timerDate: $state.timerDate,
  121. delta: $state.glucoseDelta,
  122. units: $state.units,
  123. alarm: $state.alarm,
  124. lowGlucose: $state.lowGlucose,
  125. highGlucose: $state.highGlucose
  126. )
  127. .onTapGesture {
  128. if state.alarm == nil {
  129. state.openCGM()
  130. } else {
  131. state.showModal(for: .snooze)
  132. }
  133. }
  134. .onLongPressGesture {
  135. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  136. impactHeavy.impactOccurred()
  137. if state.alarm == nil {
  138. state.showModal(for: .snooze)
  139. } else {
  140. state.openCGM()
  141. }
  142. }
  143. }
  144. var pumpView: some View {
  145. PumpView(
  146. reservoir: $state.reservoir,
  147. battery: $state.battery,
  148. name: $state.pumpName,
  149. expiresAtDate: $state.pumpExpiresAtDate,
  150. timerDate: $state.timerDate
  151. )
  152. .onTapGesture {
  153. if state.pumpDisplayState != nil {
  154. state.setupPump = true
  155. }
  156. }
  157. }
  158. var loopView: some View {
  159. LoopView(
  160. suggestion: $state.suggestion,
  161. enactedSuggestion: $state.enactedSuggestion,
  162. closedLoop: $state.closedLoop,
  163. timerDate: $state.timerDate,
  164. isLooping: $state.isLooping,
  165. lastLoopDate: $state.lastLoopDate,
  166. manualTempBasal: $state.manualTempBasal
  167. ).onTapGesture {
  168. isStatusPopupPresented = true
  169. }.onLongPressGesture {
  170. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  171. impactHeavy.impactOccurred()
  172. state.runLoop()
  173. }
  174. }
  175. var tempBasalString: String? {
  176. guard let tempRate = state.tempRate else {
  177. return nil
  178. }
  179. let rateString = numberFormatter.string(from: tempRate as NSNumber) ?? "0"
  180. var manualBasalString = ""
  181. if state.apsManager.isManualTempBasal {
  182. manualBasalString = NSLocalizedString(
  183. " - Manual Basal ⚠️",
  184. comment: "Manual Temp basal"
  185. )
  186. }
  187. return rateString + NSLocalizedString(" U/hr", comment: "Unit per hour with space") + manualBasalString
  188. }
  189. var tempTargetString: String? {
  190. guard let tempTarget = state.tempTarget else {
  191. return nil
  192. }
  193. let target = tempTarget.targetBottom ?? 0
  194. let unitString = targetFormatter.string(from: (tempTarget.targetBottom?.asMmolL ?? 0) as NSNumber) ?? ""
  195. let rawString = (tirFormatter.string(from: (tempTarget.targetBottom ?? 0) as NSNumber) ?? "") + " " + state.units
  196. .rawValue
  197. var string = ""
  198. if sliderTTpresets.first?.active ?? false {
  199. let hbt = sliderTTpresets.first?.hbt ?? 0
  200. string = ", " + (tirFormatter.string(from: state.infoPanelTTPercentage(hbt, target) as NSNumber) ?? "") + " %"
  201. }
  202. let percentString = state
  203. .units == .mmolL ? (unitString + " mmol/L" + string) : (rawString + (string == "0" ? "" : string))
  204. return tempTarget.displayName + " " + percentString
  205. }
  206. var overrideString: String? {
  207. guard fetchedPercent.first?.enabled ?? false else {
  208. return nil
  209. }
  210. var percentString = "\((fetchedPercent.first?.percentage ?? 100).formatted(.number)) %"
  211. var target = (fetchedPercent.first?.target ?? 100) as Decimal
  212. let indefinite = (fetchedPercent.first?.indefinite ?? false)
  213. let unit = state.units.rawValue
  214. if state.units == .mmolL {
  215. target = target.asMmolL
  216. }
  217. var targetString = (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " + unit
  218. if tempTargetString != nil || target == 0 { targetString = "" }
  219. percentString = percentString == "100 %" ? "" : percentString
  220. let duration = (fetchedPercent.first?.duration ?? 0) as Decimal
  221. let addedMinutes = Int(duration)
  222. let date = fetchedPercent.first?.date ?? Date()
  223. var newDuration: Decimal = 0
  224. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) > Date() {
  225. newDuration = Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes)
  226. }
  227. var durationString = indefinite ?
  228. "" : newDuration >= 1 ?
  229. (newDuration.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) + " min") :
  230. (
  231. newDuration > 0 ? (
  232. (newDuration * 60).formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) + " s"
  233. ) :
  234. ""
  235. )
  236. let smbToggleString = (fetchedPercent.first?.smbIsOff ?? false) ? " \u{20e0}" : ""
  237. var comma1 = ", "
  238. var comma2 = comma1
  239. var comma3 = comma1
  240. if targetString == "" || percentString == "" { comma1 = "" }
  241. if durationString == "" { comma2 = "" }
  242. if smbToggleString == "" { comma3 = "" }
  243. if percentString == "", targetString == "" {
  244. comma1 = ""
  245. comma2 = ""
  246. }
  247. if percentString == "", targetString == "", smbToggleString == "" {
  248. durationString = ""
  249. comma1 = ""
  250. comma2 = ""
  251. comma3 = ""
  252. }
  253. if durationString == "" {
  254. comma2 = ""
  255. }
  256. if smbToggleString == "" {
  257. comma3 = ""
  258. }
  259. if durationString == "", !indefinite {
  260. return nil
  261. }
  262. return percentString + comma1 + targetString + comma2 + durationString + comma3 + smbToggleString
  263. }
  264. var infoPanel: some View {
  265. HStack(alignment: .center) {
  266. if state.pumpSuspended {
  267. Text("Pump suspended")
  268. .font(.system(size: 12, weight: .bold)).foregroundColor(.loopGray)
  269. .padding(.leading, 8)
  270. } else if let tempBasalString = tempBasalString {
  271. Text(tempBasalString)
  272. .font(.system(size: 12, weight: .bold))
  273. .foregroundColor(.insulin)
  274. .padding(.leading, 8)
  275. }
  276. if let tempTargetString = tempTargetString {
  277. Text(tempTargetString)
  278. .font(.caption)
  279. .foregroundColor(.secondary)
  280. }
  281. Spacer()
  282. if let overrideString = overrideString {
  283. Text("👤 " + overrideString)
  284. .font(.system(size: 12))
  285. .foregroundColor(.secondary)
  286. .padding(.trailing, 8)
  287. }
  288. if state.closedLoop, state.settingsManager.preferences.maxIOB == 0 {
  289. Text("Max IOB: 0").font(.callout).foregroundColor(.orange).padding(.trailing, 20)
  290. }
  291. if let progress = state.bolusProgress {
  292. Text("Bolusing")
  293. .font(.system(size: 12, weight: .bold)).foregroundColor(.insulin)
  294. ProgressView(value: Double(progress))
  295. .progressViewStyle(BolusProgressViewStyle())
  296. .padding(.trailing, 8)
  297. .onTapGesture {
  298. state.cancelBolus()
  299. }
  300. }
  301. }
  302. .frame(maxWidth: .infinity, maxHeight: 30)
  303. }
  304. var legendPanel: some View {
  305. ZStack {
  306. HStack(alignment: .center) {
  307. Group {
  308. Circle().fill(Color.loopGreen).frame(width: 8, height: 8)
  309. Text("BG")
  310. .font(.system(size: 12, weight: .bold)).foregroundColor(.loopGreen)
  311. }
  312. Group {
  313. Circle().fill(Color.insulin).frame(width: 8, height: 8)
  314. .padding(.leading, 8)
  315. Text("IOB")
  316. .font(.system(size: 12, weight: .bold)).foregroundColor(.insulin)
  317. }
  318. Group {
  319. Circle().fill(Color.zt).frame(width: 8, height: 8)
  320. .padding(.leading, 8)
  321. Text("ZT")
  322. .font(.system(size: 12, weight: .bold)).foregroundColor(.zt)
  323. }
  324. Group {
  325. Circle().fill(Color.loopYellow).frame(width: 8, height: 8)
  326. .padding(.leading, 8)
  327. Text("COB")
  328. .font(.system(size: 12, weight: .bold)).foregroundColor(.loopYellow)
  329. }
  330. Group {
  331. Circle().fill(Color.uam).frame(width: 8, height: 8)
  332. .padding(.leading, 8)
  333. Text("UAM")
  334. .font(.system(size: 12, weight: .bold)).foregroundColor(.uam)
  335. }
  336. if let eventualBG = state.eventualBG {
  337. Text(
  338. "⇢ " + numberFormatter.string(
  339. from: (state.units == .mmolL ? eventualBG.asMmolL : Decimal(eventualBG)) as NSNumber
  340. )!
  341. )
  342. .font(.system(size: 12, weight: .bold)).foregroundColor(.secondary)
  343. }
  344. }
  345. .frame(maxWidth: .infinity)
  346. .padding([.bottom], 20)
  347. }
  348. }
  349. var mainChart: some View {
  350. ZStack {
  351. if state.animatedBackground {
  352. SpriteView(scene: spriteScene, options: [.allowsTransparency])
  353. .ignoresSafeArea()
  354. .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
  355. }
  356. MainChartView(
  357. glucose: $state.glucose,
  358. isManual: $state.isManual,
  359. suggestion: $state.suggestion,
  360. tempBasals: $state.tempBasals,
  361. boluses: $state.boluses,
  362. suspensions: $state.suspensions,
  363. announcement: $state.announcement,
  364. hours: .constant(state.filteredHours),
  365. maxBasal: $state.maxBasal,
  366. autotunedBasalProfile: $state.autotunedBasalProfile,
  367. basalProfile: $state.basalProfile,
  368. tempTargets: $state.tempTargets,
  369. carbs: $state.carbs,
  370. timerDate: $state.timerDate,
  371. units: $state.units,
  372. smooth: $state.smooth,
  373. highGlucose: $state.highGlucose,
  374. lowGlucose: $state.lowGlucose,
  375. screenHours: Binding.constant(calculateScreenHours(scale: scale)),
  376. displayXgridLines: $state.displayXgridLines,
  377. displayYgridLines: $state.displayYgridLines,
  378. thresholdLines: $state.thresholdLines
  379. )
  380. }
  381. .padding(.bottom)
  382. .modal(for: .dataTable, from: self)
  383. }
  384. // MARK: PICKER IN SEGEMENTED STYLE TO CHOOSE THE X AXIS SCALE OF THE GRAPH
  385. // _geo _: GeometryProxy
  386. @ViewBuilder private func pickerPanel(_: GeometryProxy) -> some View {
  387. ZStack {
  388. Rectangle().fill(Color.gray.opacity(0.3)).frame(maxHeight: 40)
  389. HStack {
  390. Picker("Scale", selection: $scale) {
  391. ForEach(Scale.allCases) { scale in
  392. Text(NSLocalizedString(scale.rawValue, comment: "")).tag(Optional(scale))
  393. }
  394. }
  395. .pickerStyle(.segmented).background(.cyan.opacity(0.2))
  396. }
  397. // Picker("Scale", selection: $scale) {
  398. // ForEach(Scale.allCases) { scale in
  399. // Text(NSLocalizedString(scale.rawValue, comment: "")).tag(Optional(scale))
  400. // }
  401. // }
  402. // .pickerStyle(.segmented).background(.cyan.opacity(0.2))
  403. }
  404. }
  405. private func calculateScreenHours(scale: Scale) -> Int {
  406. switch scale {
  407. case .one:
  408. return 1
  409. case .three:
  410. return 3
  411. case .six:
  412. return 6
  413. case .twelve:
  414. return 12
  415. case .twentyfour:
  416. return 24
  417. }
  418. }
  419. @ViewBuilder private func profiles(_: GeometryProxy) -> some View {
  420. let colour: Color = colorScheme == .dark ? .black : .white
  421. // Rectangle().fill(colour).frame(maxHeight: 1)
  422. ZStack {
  423. Rectangle().fill(Color.gray.opacity(0.3)).frame(maxHeight: 40)
  424. let cancel = fetchedPercent.first?.enabled ?? false
  425. HStack(spacing: cancel ? 25 : 15) {
  426. Text(selectedProfile().name).foregroundColor(.secondary)
  427. if cancel, selectedProfile().isOn {
  428. Button { showCancelAlert.toggle() }
  429. label: {
  430. Image(systemName: "xmark")
  431. .foregroundStyle(.secondary)
  432. }
  433. }
  434. Button { state.showModal(for: .overrideProfilesConfig) }
  435. label: {
  436. Image(systemName: "person.3.sequence.fill")
  437. .symbolRenderingMode(.palette)
  438. .foregroundStyle(
  439. !(fetchedPercent.first?.enabled ?? false) ? .green : .cyan,
  440. !(fetchedPercent.first?.enabled ?? false) ? .cyan : .green,
  441. .purple
  442. )
  443. }
  444. }
  445. }
  446. .alert(
  447. "Return to Normal?", isPresented: $showCancelAlert,
  448. actions: {
  449. Button("No", role: .cancel) {}
  450. Button("Yes", role: .destructive) {
  451. state.cancelProfile()
  452. }
  453. }, message: { Text("This will change settings back to your normal profile.") }
  454. )
  455. Rectangle().fill(colour).frame(maxHeight: 1)
  456. }
  457. private func selectedProfile() -> (name: String, isOn: Bool) {
  458. var profileString = ""
  459. var display: Bool = false
  460. let duration = (fetchedPercent.first?.duration ?? 0) as Decimal
  461. let indefinite = fetchedPercent.first?.indefinite ?? false
  462. let addedMinutes = Int(duration)
  463. let date = fetchedPercent.first?.date ?? Date()
  464. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) > Date() || indefinite {
  465. display.toggle()
  466. }
  467. if fetchedPercent.first?.enabled ?? false, !(fetchedPercent.first?.isPreset ?? false), display {
  468. profileString = NSLocalizedString("Custom Profile", comment: "Custom but unsaved Profile")
  469. } else if !(fetchedPercent.first?.enabled ?? false) || !display {
  470. profileString = NSLocalizedString("Normal Profile", comment: "Your normal Profile. Use a short string")
  471. } else {
  472. let id_ = fetchedPercent.first?.id ?? ""
  473. let profile = fetchedProfiles.filter({ $0.id == id_ }).first
  474. if profile != nil {
  475. profileString = profile?.name?.description ?? ""
  476. }
  477. }
  478. return (name: profileString, isOn: display)
  479. }
  480. @ViewBuilder private func bottomPanel(_ geo: GeometryProxy) -> some View {
  481. ZStack {
  482. Rectangle().fill(Color.gray.opacity(0.3)).frame(height: 50 + geo.safeAreaInsets.bottom)
  483. HStack {
  484. Button { state.showModal(for: .addCarbs(editMode: false, override: false)) }
  485. label: {
  486. ZStack(alignment: Alignment(horizontal: .trailing, vertical: .bottom)) {
  487. Image("carbs")
  488. .renderingMode(.template)
  489. .resizable()
  490. .frame(width: 24, height: 24)
  491. .foregroundColor(.loopYellow)
  492. .padding(8)
  493. if let carbsReq = state.carbsRequired {
  494. Text(numberFormatter.string(from: carbsReq as NSNumber)!)
  495. .font(.caption)
  496. .foregroundColor(.white)
  497. .padding(4)
  498. .background(Capsule().fill(Color.red))
  499. }
  500. }
  501. }.buttonStyle(.borderless)
  502. Spacer()
  503. Button { state.showModal(for: .addTempTarget) }
  504. label: {
  505. Image("target")
  506. .renderingMode(.template)
  507. .resizable()
  508. .frame(width: 24, height: 24)
  509. .padding(8)
  510. }
  511. .foregroundColor(.loopGreen)
  512. .buttonStyle(.borderless)
  513. Spacer()
  514. Button {
  515. state.showModal(for: .bolus(
  516. waitForSuggestion: true,
  517. fetch: false
  518. ))
  519. }
  520. label: {
  521. Image("bolus")
  522. .renderingMode(.template)
  523. .resizable()
  524. .frame(width: 24, height: 24)
  525. .padding(8)
  526. }
  527. .foregroundColor(.insulin)
  528. .buttonStyle(.borderless)
  529. Spacer()
  530. if state.allowManualTemp {
  531. Button { state.showModal(for: .manualTempBasal) }
  532. label: {
  533. Image("bolus1")
  534. .renderingMode(.template)
  535. .resizable()
  536. .frame(width: 24, height: 24)
  537. .padding(8)
  538. }
  539. .foregroundColor(.insulin)
  540. .buttonStyle(.borderless)
  541. Spacer()
  542. }
  543. Button { state.showModal(for: .statistics)
  544. }
  545. label: {
  546. Image(systemName: "chart.xyaxis.line")
  547. .renderingMode(.template)
  548. .resizable()
  549. .frame(width: 24, height: 24)
  550. .padding(8)
  551. }
  552. .foregroundColor(.purple)
  553. .buttonStyle(.borderless)
  554. Spacer()
  555. Button { state.showModal(for: .settings) }
  556. label: {
  557. Image("settings1")
  558. .renderingMode(.template)
  559. .resizable()
  560. .frame(width: 24, height: 24)
  561. .padding(8)
  562. }
  563. .foregroundColor(.loopGray)
  564. .buttonStyle(.borderless)
  565. }
  566. .padding(.horizontal, 24)
  567. .padding(.bottom, geo.safeAreaInsets.bottom)
  568. }
  569. }
  570. var body: some View {
  571. GeometryReader { geo in
  572. VStack(spacing: 0) {
  573. header(geo)
  574. infoPanel
  575. mainChart
  576. legendPanel
  577. pickerPanel(geo)
  578. profiles(geo)
  579. bottomPanel(geo)
  580. }
  581. .edgesIgnoringSafeArea(.vertical)
  582. }
  583. .onAppear(perform: configureView)
  584. .navigationTitle("Home")
  585. .navigationBarHidden(true)
  586. .ignoresSafeArea(.keyboard)
  587. .popup(isPresented: isStatusPopupPresented, alignment: .top, direction: .top) {
  588. popup
  589. .padding()
  590. .background(
  591. RoundedRectangle(cornerRadius: 8, style: .continuous)
  592. .fill(Color(UIColor.darkGray))
  593. )
  594. .onTapGesture {
  595. isStatusPopupPresented = false
  596. }
  597. .gesture(
  598. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  599. .onEnded { value in
  600. if value.translation.height < 0 {
  601. isStatusPopupPresented = false
  602. }
  603. }
  604. )
  605. }
  606. }
  607. private var popup: some View {
  608. VStack(alignment: .leading, spacing: 4) {
  609. Text(state.statusTitle).font(.headline).foregroundColor(.white)
  610. .padding(.bottom, 4)
  611. if let suggestion = state.suggestion {
  612. TagCloudView(tags: suggestion.reasonParts).animation(.none, value: false)
  613. Text(suggestion.reasonConclusion.capitalizingFirstLetter()).font(.caption).foregroundColor(.white)
  614. } else {
  615. Text("No sugestion found").font(.body).foregroundColor(.white)
  616. }
  617. if let errorMessage = state.errorMessage, let date = state.errorDate {
  618. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  619. .foregroundColor(.white)
  620. .font(.headline)
  621. .padding(.bottom, 4)
  622. .padding(.top, 8)
  623. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  624. } else if let suggestion = state.suggestion, (suggestion.bg ?? 100) == 400 {
  625. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  626. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  627. }
  628. }
  629. }
  630. }
  631. }