HomeRootView.swift 32 KB

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