HomeRootView.swift 34 KB

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