HomeRootView.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  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: true, 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 {
  408. state.showModal(for: .dataTable)
  409. }
  410. label: {
  411. if #available(iOS 17.0, *) {
  412. Image(systemName: "book.pages")
  413. .font(.system(size: 24))
  414. .foregroundColor(colorIcon)
  415. .padding(8)
  416. } else {
  417. Image(systemName: "book")
  418. .font(.system(size: 24))
  419. .foregroundColor(colorIcon)
  420. .padding(8)
  421. }
  422. }
  423. .foregroundColor(colorIcon)
  424. .buttonStyle(.borderless)
  425. Spacer()
  426. Button { state.showModal(for: .addCarbs(editMode: false, override: false)) }
  427. label: {
  428. ZStack(alignment: Alignment(horizontal: .trailing, vertical: .bottom)) {
  429. Image(systemName: "fork.knife")
  430. .font(.system(size: 24))
  431. .foregroundColor(colorIcon)
  432. .padding(8)
  433. if let carbsReq = state.carbsRequired {
  434. Text(numberFormatter.string(from: carbsReq as NSNumber)!)
  435. .font(.caption)
  436. .foregroundColor(.white)
  437. .padding(4)
  438. .background(Capsule().fill(Color.red))
  439. }
  440. }
  441. }.buttonStyle(.borderless)
  442. Spacer()
  443. // Button { state.showModal(for: .addTempTarget) }
  444. // label: {
  445. // Image(systemName: "target")
  446. // .font(.system(size: 24))
  447. // .padding(8)
  448. // }
  449. // .foregroundColor(state.isTempTargetActive ? Color.purple : colorIcon)
  450. // .buttonStyle(.borderless)
  451. // Spacer()
  452. Button {
  453. state.showModal(for: .bolus(
  454. waitForSuggestion: true,
  455. fetch: false
  456. ))
  457. }
  458. label: {
  459. Image(systemName: "syringe.fill")
  460. .font(.system(size: 24))
  461. .foregroundColor(colorIcon)
  462. .padding(8)
  463. }
  464. .foregroundColor(colorIcon)
  465. .buttonStyle(.borderless)
  466. Spacer()
  467. if state.allowManualTemp {
  468. Button { state.showModal(for: .manualTempBasal) }
  469. label: {
  470. Image("bolus1")
  471. .renderingMode(.template)
  472. .resizable()
  473. .frame(width: 24, height: 24)
  474. .padding(8)
  475. }
  476. .foregroundColor(colorIcon)
  477. .buttonStyle(.borderless)
  478. Spacer()
  479. }
  480. // MARK: CANCEL OF PROFILE HAS TO BE IMPLEMENTED
  481. // MAYBE WITH A SMALL INDICATOR AT THE SYMBOL
  482. Button {
  483. state.showModal(for: .overrideProfilesConfig)
  484. } label: {
  485. Image(systemName: "person")
  486. .font(.system(size: 26))
  487. .padding(8)
  488. }
  489. .foregroundColor((state.isTempTargetActive || (overrideString != nil)) ? Color.purple : colorIcon)
  490. .buttonStyle(.borderless)
  491. Spacer()
  492. Button { state.showModal(for: .statistics)
  493. }
  494. label: {
  495. Image(systemName: "chart.pie")
  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: 14))
  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: 14))
  614. }
  615. }
  616. }
  617. }
  618. @ViewBuilder func mealPanel(_: GeometryProxy) -> some View {
  619. HStack(spacing: 40) {
  620. HStack {
  621. Image(systemName: "syringe.fill")
  622. .font(.system(size: 15))
  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: 15))
  629. }
  630. HStack {
  631. Image(systemName: "fork.knife")
  632. .font(.system(size: 15))
  633. .foregroundColor(.loopYellow)
  634. Text(
  635. (numberFormatter.string(from: (state.suggestion?.cob ?? 0) as NSNumber) ?? "0") +
  636. NSLocalizedString(" g", comment: "gram of carbs")
  637. )
  638. .font(.system(size: 15))
  639. }
  640. HStack {
  641. if state.pumpSuspended {
  642. Text("Pump suspended")
  643. .font(.system(size: 12)).foregroundColor(.loopGray)
  644. } else if let tempBasalString = tempBasalString {
  645. Text(tempBasalString)
  646. .font(.system(size: 15))
  647. .foregroundColor(.insulin)
  648. }
  649. }
  650. if !state.tins {
  651. HStack {
  652. Text(
  653. "TDD: " +
  654. (numberFormatter.string(from: (state.suggestion?.tdd ?? 0) as NSNumber) ?? "--") +
  655. NSLocalizedString(" U", comment: "Insulin unit")
  656. ).font(.system(size: 15))
  657. }
  658. } else {
  659. Text(
  660. "TINS: \(state.calculateTINS())" +
  661. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  662. )
  663. .font(.system(size: 15))
  664. .foregroundColor(.insulin)
  665. }
  666. }
  667. }
  668. @ViewBuilder func profileView(_: GeometryProxy) -> some View {
  669. let colourChart: Color = colorScheme == .dark ? Color(
  670. red: 0.05490196078,
  671. green: 0.05490196078,
  672. blue: 0.05490196078
  673. ) : .white
  674. if let overrideString = overrideString {
  675. ZStack {
  676. /// rectangle as background
  677. RoundedRectangle(cornerRadius: 15)
  678. .fill(colourChart)
  679. .clipShape(RoundedRectangle(cornerRadius: 15))
  680. .frame(height: UIScreen.main.bounds.height / 20)
  681. .shadow(
  682. color:
  683. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  684. radius: 1
  685. )
  686. HStack {
  687. /// actual profile view
  688. Image(systemName: "person.fill")
  689. .font(.system(size: 20))
  690. .foregroundStyle(Color.purple)
  691. Spacer()
  692. Text(overrideString)
  693. .font(.system(size: 18))
  694. Spacer()
  695. Image(systemName: "xmark.app")
  696. .font(.system(size: 20))
  697. }.padding(.horizontal, 10)
  698. .alert(
  699. "Return to Normal?", isPresented: $showCancelAlert,
  700. actions: {
  701. Button("No", role: .cancel) {}
  702. Button("Yes", role: .destructive) {
  703. state.cancelProfile()
  704. }
  705. }, message: { Text("This will change settings back to your normal profile.") }
  706. )
  707. .padding(.trailing, 8)
  708. .onTapGesture {
  709. showCancelAlert = true
  710. }
  711. }.padding(.horizontal, 10)
  712. }
  713. /// just show temp target if no profile is already active
  714. if overrideString == nil, let tempTargetString = tempTargetString {
  715. ZStack {
  716. /// rectangle as background
  717. RoundedRectangle(cornerRadius: 15)
  718. .fill(colourChart)
  719. .clipShape(RoundedRectangle(cornerRadius: 15))
  720. .frame(height: UIScreen.main.bounds.height / 20)
  721. .shadow(
  722. color:
  723. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  724. radius: 1
  725. )
  726. HStack {
  727. Image(systemName: "person.fill")
  728. .font(.system(size: 20))
  729. .foregroundStyle(Color.purple)
  730. Spacer()
  731. Text(tempTargetString)
  732. .font(.system(size: 15))
  733. Spacer()
  734. }.padding(.horizontal, 10)
  735. }.padding(.horizontal, 10)
  736. }
  737. }
  738. var body: some View {
  739. let colorBackground = colorScheme == .dark ? LinearGradient(
  740. gradient: Gradient(colors: [
  741. // RGB(3, 15, 28)
  742. Color(red: 0.011, green: 0.058, blue: 0.109),
  743. // RGB(10, 34, 55)
  744. Color(red: 0.03921568627, green: 0.1333333333, blue: 0.2156862745)
  745. ]),
  746. startPoint: .bottom,
  747. endPoint: .top
  748. )
  749. :
  750. LinearGradient(gradient: Gradient(colors: [Color.gray.opacity(0.1)]), startPoint: .top, endPoint: .bottom)
  751. let colourChart: Color = colorScheme == .dark ? Color(
  752. red: 0.05490196078,
  753. green: 0.05490196078,
  754. blue: 0.05490196078
  755. ) : .white
  756. GeometryReader { geo in
  757. VStack(spacing: 0) {
  758. Spacer()
  759. ZStack {
  760. /// glucose bobble
  761. glucoseView
  762. /// right panel with loop status and evBG
  763. HStack {
  764. Spacer()
  765. rightHeaderPanel(geo)
  766. }.padding(.trailing, 20)
  767. /// left panel with pump related info
  768. HStack {
  769. pumpView
  770. Spacer()
  771. }.padding(.leading, 20)
  772. }.padding(.top, 40)
  773. mealPanel(geo).padding(.top, 20)
  774. Spacer()
  775. profileView(geo).padding(.vertical)
  776. RoundedRectangle(cornerRadius: 15)
  777. .fill(colourChart)
  778. .overlay(mainChart)
  779. .clipShape(RoundedRectangle(cornerRadius: 15))
  780. .shadow(
  781. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  782. Color.black.opacity(0.33),
  783. radius: 3
  784. )
  785. .padding(.horizontal, 10)
  786. .frame(maxHeight: UIScreen.main.bounds.height / 2.1)
  787. Spacer()
  788. timeInterval
  789. Spacer()
  790. ZStack(alignment: .bottom) {
  791. bottomPanel(geo)
  792. if let progress = state.bolusProgress {
  793. bolusProgressView(geo, progress)
  794. }
  795. }
  796. }
  797. .background(colorBackground)
  798. .edgesIgnoringSafeArea(.all)
  799. }
  800. .onChange(of: state.hours) { _ in
  801. highlightButtons()
  802. }
  803. .onAppear {
  804. configureView {
  805. highlightButtons()
  806. }
  807. }
  808. .navigationTitle("Home")
  809. .navigationBarHidden(true)
  810. .ignoresSafeArea(.keyboard)
  811. .popup(isPresented: state.isStatusPopupPresented, alignment: .top, direction: .top) {
  812. popup
  813. .padding()
  814. .background(
  815. RoundedRectangle(cornerRadius: 8, style: .continuous)
  816. .fill(colorScheme == .dark ? Color(
  817. red: 0.05490196078,
  818. green: 0.05490196078,
  819. blue: 0.05490196078
  820. ) : Color(UIColor.darkGray))
  821. )
  822. .onTapGesture {
  823. state.isStatusPopupPresented = false
  824. }
  825. .gesture(
  826. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  827. .onEnded { value in
  828. if value.translation.height < 0 {
  829. state.isStatusPopupPresented = false
  830. }
  831. }
  832. )
  833. }
  834. }
  835. private var popup: some View {
  836. VStack(alignment: .leading, spacing: 4) {
  837. Text(state.statusTitle).font(.headline).foregroundColor(.white)
  838. .padding(.bottom, 4)
  839. if let suggestion = state.suggestion {
  840. TagCloudView(tags: suggestion.reasonParts).animation(.none, value: false)
  841. Text(suggestion.reasonConclusion.capitalizingFirstLetter()).font(.caption).foregroundColor(.white)
  842. } else {
  843. Text("No sugestion found").font(.body).foregroundColor(.white)
  844. }
  845. if let errorMessage = state.errorMessage, let date = state.errorDate {
  846. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  847. .foregroundColor(.white)
  848. .font(.headline)
  849. .padding(.bottom, 4)
  850. .padding(.top, 8)
  851. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  852. } else if let suggestion = state.suggestion, (suggestion.bg ?? 100) == 400 {
  853. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  854. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  855. }
  856. }
  857. }
  858. }
  859. }