HomeRootView.swift 40 KB

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