HomeRootView.swift 33 KB

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