HomeRootView.swift 36 KB

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