HomeRootView.swift 38 KB

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