HomeRootView.swift 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  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 menuSymbols(action: @escaping () -> Void, systemName: String) -> some View {
  689. Button(
  690. action: action,
  691. label: {
  692. HStack {
  693. Image(systemName: systemName)
  694. .font(.system(size: 21))
  695. .foregroundStyle(colorScheme == .dark ? .white : .black)
  696. }.padding(.top, 1)
  697. }
  698. )
  699. }
  700. @ViewBuilder func menuElements(action: @escaping () -> Void, title: String) -> some View {
  701. Button(
  702. action: action,
  703. label: {
  704. HStack {
  705. Text(title)
  706. .font(.system(size: 19))
  707. .foregroundStyle(colorScheme == .dark ? .white : .black)
  708. Spacer()
  709. Image(systemName: "arrow.right")
  710. .font(.system(size: 21))
  711. .foregroundStyle(colorScheme == .dark ? .white : .black)
  712. }.padding(.top, 1)
  713. }
  714. )
  715. }
  716. @ViewBuilder func sideMenuView() -> some View {
  717. ZStack {
  718. RoundedRectangle(cornerRadius: 8)
  719. .fill(color)
  720. .shadow(
  721. color: Color.black.opacity(0.33),
  722. radius: 3
  723. )
  724. .ignoresSafeArea(edges: .all)
  725. VStack(alignment: .leading) {
  726. Button {
  727. isMenuPresented.toggle()
  728. } label: {
  729. HStack {
  730. Image(systemName: "arrow.left")
  731. .font(.system(size: 30))
  732. .foregroundStyle(colorScheme == .dark ? .white : .black)
  733. Text("Menu")
  734. .font(.system(size: 30)).fontWeight(.bold)
  735. .foregroundStyle(colorScheme == .dark ? .white : .black)
  736. }
  737. }
  738. .padding(.top, 60)
  739. HStack(spacing: 15) {
  740. VStack(alignment: .leading, spacing: 25, content: {
  741. menuSymbols(action: { state.showModal(for: .statistics) }, systemName: "chart.bar.xaxis")
  742. .padding(.top, 20)
  743. menuSymbols(action: {
  744. if state.pumpDisplayState != nil {
  745. state.setupPump = true
  746. }
  747. }, systemName: "cross.vial.fill")
  748. menuSymbols(action: {
  749. if state.alarm == nil {
  750. state.openCGM()
  751. } else {
  752. state.showModal(for: .snooze)
  753. }
  754. }, systemName: "sensor.tag.radiowaves.forward.fill")
  755. menuSymbols(action: { state.showModal(for: .addTempTarget) }, systemName: "target")
  756. menuSymbols(action: { state.showModal(for: .settings) }, systemName: "gear")
  757. Spacer()
  758. })
  759. VStack(alignment: .leading, spacing: 25, content: {
  760. menuElements(action: { state.showModal(for: .statistics) }, title: "Statistics")
  761. .padding(.top, 20)
  762. menuElements(action: {
  763. if state.pumpDisplayState != nil {
  764. state.setupPump = true
  765. }
  766. }, title: "Pump Settings")
  767. menuElements(action: {
  768. if state.alarm == nil {
  769. state.openCGM()
  770. } else {
  771. state.showModal(for: .snooze)
  772. }
  773. }, title: "CGM")
  774. menuElements(action: { state.showModal(for: .addTempTarget) }, title: "Temp targets")
  775. menuElements(action: { state.showModal(for: .settings) }, title: "Settings")
  776. Spacer()
  777. })
  778. }
  779. }.padding(.horizontal, 25)
  780. }
  781. .frame(width: UIScreen.main.bounds.width / 1.2, height: UIScreen.main.bounds.height - 20)
  782. }
  783. @ViewBuilder func mainView() -> some View {
  784. GeometryReader { geo in
  785. ZStack(alignment: .trailing) {
  786. VStack(spacing: 0) {
  787. ZStack {
  788. /// glucose bobble
  789. glucoseView
  790. /// right panel with loop status and evBG
  791. HStack {
  792. Spacer()
  793. rightHeaderPanel(geo)
  794. }.padding(.trailing, 20)
  795. /// left panel with pump related info
  796. HStack {
  797. pumpView
  798. Spacer()
  799. }.padding(.leading, 20)
  800. HStack {
  801. Spacer()
  802. Button {
  803. isMenuPresented.toggle()
  804. }
  805. label: {
  806. Image(systemName: "text.justify")
  807. .font(.body).foregroundStyle(colorScheme == .dark ? Color.white : Color.black)
  808. }.padding(.trailing, 20).padding(.bottom, 110)
  809. }
  810. }.padding(.top, 70)
  811. mealPanel(geo).padding(.vertical, 25)
  812. profileView(geo).padding(.vertical)
  813. RoundedRectangle(cornerRadius: 15)
  814. .fill(Color.chart)
  815. .overlay(mainChart)
  816. .clipShape(RoundedRectangle(cornerRadius: 15))
  817. .shadow(
  818. color: colorScheme == .dark ? Color(
  819. red: 0.02745098039,
  820. green: 0.1098039216,
  821. blue: 0.1411764706
  822. ) :
  823. Color.black.opacity(0.33),
  824. radius: 3
  825. )
  826. .padding(.horizontal, 10)
  827. .frame(maxHeight: UIScreen.main.bounds.height / 2.1)
  828. timeInterval.padding(.top, 25)
  829. Spacer()
  830. ZStack(alignment: .bottom) {
  831. // bottomPanel(geo)
  832. if let progress = state.bolusProgress {
  833. bolusProgressView(geo, progress)
  834. }
  835. }
  836. }
  837. // tabbar
  838. }
  839. .background(color)
  840. .blur(radius: isMenuPresented ? 5 : 0)
  841. .edgesIgnoringSafeArea(.all)
  842. }
  843. .onChange(of: state.hours) { _ in
  844. highlightButtons()
  845. }
  846. .onAppear {
  847. configureView {
  848. highlightButtons()
  849. }
  850. }
  851. .navigationTitle("Home")
  852. .navigationBarHidden(true)
  853. .ignoresSafeArea(.keyboard)
  854. .popup(isPresented: state.isStatusPopupPresented, alignment: .top, direction: .top) {
  855. popup
  856. .padding()
  857. .background(
  858. RoundedRectangle(cornerRadius: 8, style: .continuous)
  859. .fill(colorScheme == .dark ? Color(
  860. "Chart"
  861. ) : Color(UIColor.darkGray))
  862. )
  863. .onTapGesture {
  864. state.isStatusPopupPresented = false
  865. }
  866. .gesture(
  867. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  868. .onEnded { value in
  869. if value.translation.height < 0 {
  870. state.isStatusPopupPresented = false
  871. }
  872. }
  873. )
  874. }
  875. }
  876. @ViewBuilder func tapBar() -> some View {
  877. TabView {
  878. mainView().tabItem { Label("Home", systemImage: "house") }
  879. NavigationStack { DataTable.RootView(resolver: resolver) }
  880. .tabItem { Label("History", systemImage: historySFSymbol) }
  881. NavigationStack { AddCarbs.RootView(resolver: resolver, editMode: false, override: false) }
  882. .tabItem { Label("Carbs", systemImage: "fork.knife") }
  883. NavigationStack { Bolus.RootView(resolver: resolver, waitForSuggestion: false, fetch: false) }
  884. .tabItem { Label("Bolus", systemImage: "syringe.fill") }
  885. NavigationStack { OverrideProfilesConfig.RootView(resolver: resolver) }
  886. .tabItem {
  887. Label(
  888. "Profile",
  889. systemImage: state.isTempTargetActive || overrideString != nil ? "person.fill" : "person"
  890. ) }
  891. }.tint(Color.tapBar)
  892. }
  893. var body: some View {
  894. ZStack(alignment: .trailing) {
  895. tapBar()
  896. // burger menu
  897. if isMenuPresented {
  898. HStack {
  899. sideMenuView().background(Color.chart).ignoresSafeArea(.all)
  900. }
  901. }
  902. }
  903. }
  904. private var popup: some View {
  905. VStack(alignment: .leading, spacing: 4) {
  906. Text(state.statusTitle).font(.headline).foregroundColor(.white)
  907. .padding(.bottom, 4)
  908. if let suggestion = state.suggestion {
  909. TagCloudView(tags: suggestion.reasonParts).animation(.none, value: false)
  910. Text(suggestion.reasonConclusion.capitalizingFirstLetter()).font(.caption).foregroundColor(.white)
  911. } else {
  912. Text("No sugestion found").font(.body).foregroundColor(.white)
  913. }
  914. if let errorMessage = state.errorMessage, let date = state.errorDate {
  915. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  916. .foregroundColor(.white)
  917. .font(.headline)
  918. .padding(.bottom, 4)
  919. .padding(.top, 8)
  920. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  921. } else if let suggestion = state.suggestion, (suggestion.bg ?? 100) == 400 {
  922. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  923. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  924. }
  925. }
  926. }
  927. }
  928. }