HomeRootView.swift 40 KB

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