HomeRootView.swift 29 KB

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