HomeRootView.swift 40 KB

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