HomeRootView.swift 43 KB

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