HomeRootView.swift 30 KB

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