HomeRootView.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  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. @FetchRequest(
  48. entity: UXSettings.entity(),
  49. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  50. ) var fetchedSettings: FetchedResults<UXSettings>
  51. private var numberFormatter: NumberFormatter {
  52. let formatter = NumberFormatter()
  53. formatter.numberStyle = .decimal
  54. formatter.maximumFractionDigits = 2
  55. return formatter
  56. }
  57. private var fetchedTargetFormatter: NumberFormatter {
  58. let formatter = NumberFormatter()
  59. formatter.numberStyle = .decimal
  60. if state.units == .mmolL {
  61. formatter.maximumFractionDigits = 1
  62. } else { formatter.maximumFractionDigits = 0 }
  63. return formatter
  64. }
  65. private var targetFormatter: NumberFormatter {
  66. let formatter = NumberFormatter()
  67. formatter.numberStyle = .decimal
  68. formatter.maximumFractionDigits = 1
  69. return formatter
  70. }
  71. private var tirFormatter: NumberFormatter {
  72. let formatter = NumberFormatter()
  73. formatter.numberStyle = .decimal
  74. formatter.maximumFractionDigits = 0
  75. return formatter
  76. }
  77. private var dateFormatter: DateFormatter {
  78. let dateFormatter = DateFormatter()
  79. dateFormatter.timeStyle = .short
  80. return dateFormatter
  81. }
  82. private var spriteScene: SKScene {
  83. let scene = SnowScene()
  84. scene.scaleMode = .resizeFill
  85. scene.backgroundColor = .clear
  86. return scene
  87. }
  88. @ViewBuilder func header(_: GeometryProxy) -> some View {
  89. HStack {
  90. Spacer()
  91. pumpView
  92. Spacer()
  93. }
  94. }
  95. var cobIobView: some View {
  96. VStack(alignment: .leading, spacing: 12) {
  97. HStack {
  98. Text("IOB").font(.footnote).foregroundColor(.secondary)
  99. Text(
  100. (numberFormatter.string(from: (state.suggestion?.iob ?? 0) as NSNumber) ?? "0") +
  101. NSLocalizedString(" U", comment: "Insulin unit")
  102. )
  103. .font(.footnote).fontWeight(.bold)
  104. }.frame(alignment: .top)
  105. HStack {
  106. Text("COB").font(.footnote).foregroundColor(.secondary)
  107. Text(
  108. (numberFormatter.string(from: (state.suggestion?.cob ?? 0) as NSNumber) ?? "0") +
  109. NSLocalizedString(" g", comment: "gram of carbs")
  110. )
  111. .font(.footnote).fontWeight(.bold)
  112. }.frame(alignment: .bottom)
  113. }
  114. }
  115. var cobIobView2: some View {
  116. HStack {
  117. Text("IOB").font(.callout).foregroundColor(.secondary)
  118. Text(
  119. (numberFormatter.string(from: (state.suggestion?.iob ?? 0) as NSNumber) ?? "0") +
  120. NSLocalizedString(" U", comment: "Insulin unit")
  121. )
  122. .font(.callout).fontWeight(.bold)
  123. Spacer()
  124. Text("COB").font(.callout).foregroundColor(.secondary)
  125. Text(
  126. (numberFormatter.string(from: (state.suggestion?.cob ?? 0) as NSNumber) ?? "0") +
  127. NSLocalizedString(" g", comment: "gram of carbs")
  128. )
  129. .font(.callout).fontWeight(.bold)
  130. Spacer()
  131. }
  132. }
  133. var glucoseView: some View {
  134. CurrentGlucoseView(
  135. recentGlucose: $state.recentGlucose,
  136. timerDate: $state.timerDate,
  137. delta: $state.glucoseDelta,
  138. units: $state.units,
  139. alarm: $state.alarm,
  140. lowGlucose: $state.lowGlucose,
  141. highGlucose: $state.highGlucose
  142. )
  143. .onTapGesture {
  144. if state.alarm == nil {
  145. state.openCGM()
  146. } else {
  147. state.showModal(for: .snooze)
  148. }
  149. }
  150. .onLongPressGesture {
  151. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  152. impactHeavy.impactOccurred()
  153. if state.alarm == nil {
  154. state.showModal(for: .snooze)
  155. } else {
  156. state.openCGM()
  157. }
  158. }
  159. }
  160. var pumpView: some View {
  161. PumpView(
  162. reservoir: $state.reservoir,
  163. battery: $state.battery,
  164. name: $state.pumpName,
  165. expiresAtDate: $state.pumpExpiresAtDate,
  166. timerDate: $state.timerDate,
  167. state: state
  168. )
  169. .onTapGesture {
  170. if state.pumpDisplayState != nil {
  171. state.setupPump = true
  172. }
  173. }
  174. }
  175. var loopView: some View {
  176. LoopView(
  177. suggestion: $state.suggestion,
  178. enactedSuggestion: $state.enactedSuggestion,
  179. closedLoop: $state.closedLoop,
  180. timerDate: $state.timerDate,
  181. isLooping: $state.isLooping,
  182. lastLoopDate: $state.lastLoopDate,
  183. manualTempBasal: $state.manualTempBasal
  184. ).onTapGesture {
  185. isStatusPopupPresented = true
  186. }.onLongPressGesture {
  187. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  188. impactHeavy.impactOccurred()
  189. state.runLoop()
  190. }
  191. }
  192. var tempBasalString: String? {
  193. guard let tempRate = state.tempRate else {
  194. return nil
  195. }
  196. let rateString = numberFormatter.string(from: tempRate as NSNumber) ?? "0"
  197. var manualBasalString = ""
  198. if state.apsManager.isManualTempBasal {
  199. manualBasalString = NSLocalizedString(
  200. " - Manual Basal ⚠️",
  201. comment: "Manual Temp basal"
  202. )
  203. }
  204. return rateString + " " + NSLocalizedString(" U/hr", comment: "Unit per hour with space") + manualBasalString
  205. }
  206. var tempTargetString: String? {
  207. guard let tempTarget = state.tempTarget else {
  208. return nil
  209. }
  210. let target = tempTarget.targetBottom ?? 0
  211. let unitString = targetFormatter.string(from: (tempTarget.targetBottom?.asMmolL ?? 0) as NSNumber) ?? ""
  212. let rawString = (tirFormatter.string(from: (tempTarget.targetBottom ?? 0) as NSNumber) ?? "") + " " + state.units
  213. .rawValue
  214. var string = ""
  215. if sliderTTpresets.first?.active ?? false {
  216. let hbt = sliderTTpresets.first?.hbt ?? 0
  217. string = ", " + (tirFormatter.string(from: state.infoPanelTTPercentage(hbt, target) as NSNumber) ?? "") + " %"
  218. }
  219. let percentString = state
  220. .units == .mmolL ? (unitString + " mmol/L" + string) : (rawString + (string == "0" ? "" : string))
  221. return tempTarget.displayName + " " + percentString
  222. }
  223. var overrideString: String? {
  224. guard fetchedPercent.first?.enabled ?? false else {
  225. return nil
  226. }
  227. var percentString = "\((fetchedPercent.first?.percentage ?? 100).formatted(.number)) %"
  228. var target = (fetchedPercent.first?.target ?? 100) as Decimal
  229. let indefinite = (fetchedPercent.first?.indefinite ?? false)
  230. let unit = state.units.rawValue
  231. if state.units == .mmolL {
  232. target = target.asMmolL
  233. }
  234. var targetString = (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " + unit
  235. if tempTargetString != nil || target == 0 { targetString = "" }
  236. percentString = percentString == "100 %" ? "" : percentString
  237. let duration = (fetchedPercent.first?.duration ?? 0) as Decimal
  238. let addedMinutes = Int(duration)
  239. let date = fetchedPercent.first?.date ?? Date()
  240. var newDuration: Decimal = 0
  241. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) > Date() {
  242. newDuration = Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes)
  243. }
  244. var durationString = indefinite ?
  245. "" : newDuration >= 1 ?
  246. (newDuration.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) + " min") :
  247. (
  248. newDuration > 0 ? (
  249. (newDuration * 60).formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))) + " s"
  250. ) :
  251. ""
  252. )
  253. let smbToggleString = (fetchedPercent.first?.smbIsOff ?? false) ? " \u{20e0}" : ""
  254. var comma1 = ", "
  255. var comma2 = comma1
  256. var comma3 = comma1
  257. if targetString == "" || percentString == "" { comma1 = "" }
  258. if durationString == "" { comma2 = "" }
  259. if smbToggleString == "" { comma3 = "" }
  260. if percentString == "", targetString == "" {
  261. comma1 = ""
  262. comma2 = ""
  263. }
  264. if percentString == "", targetString == "", smbToggleString == "" {
  265. durationString = ""
  266. comma1 = ""
  267. comma2 = ""
  268. comma3 = ""
  269. }
  270. if durationString == "" {
  271. comma2 = ""
  272. }
  273. if smbToggleString == "" {
  274. comma3 = ""
  275. }
  276. if durationString == "", !indefinite {
  277. return nil
  278. }
  279. return percentString + comma1 + targetString + comma2 + durationString + comma3 + smbToggleString
  280. }
  281. var infoPanel: some View {
  282. HStack(alignment: .center) {
  283. if state.pumpSuspended {
  284. Text("Pump suspended")
  285. .font(.system(size: 12, weight: .bold)).foregroundColor(.loopGray)
  286. .padding(.leading, 8)
  287. } else if let tempBasalString = tempBasalString {
  288. Text(tempBasalString)
  289. .font(.system(size: 12, weight: .bold))
  290. .foregroundColor(.insulin)
  291. .padding(.leading, 8)
  292. Text(
  293. "TINS: \(state.calculateTINS())" +
  294. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  295. )
  296. .font(.system(size: 12, weight: .bold))
  297. .foregroundColor(.insulin)
  298. }
  299. if let tempTargetString = tempTargetString {
  300. Text(tempTargetString)
  301. .font(.caption)
  302. .foregroundColor(.secondary)
  303. }
  304. Spacer()
  305. if let overrideString = overrideString {
  306. Text("👤 " + overrideString)
  307. .font(.system(size: 12))
  308. .foregroundColor(.secondary)
  309. .padding(.trailing, 8)
  310. }
  311. if state.closedLoop, state.settingsManager.preferences.maxIOB == 0 {
  312. Text("Max IOB: 0").font(.callout).foregroundColor(.orange).padding(.trailing, 20)
  313. }
  314. if let progress = state.bolusProgress {
  315. Text("Bolusing")
  316. .font(.system(size: 12, weight: .bold)).foregroundColor(.insulin)
  317. ProgressView(value: Double(progress))
  318. .progressViewStyle(BolusProgressViewStyle())
  319. .padding(.trailing, 8)
  320. .onTapGesture {
  321. state.cancelBolus()
  322. }
  323. }
  324. }
  325. .frame(maxWidth: .infinity, maxHeight: 30)
  326. }
  327. var legendPanel: some View {
  328. ZStack {
  329. HStack(alignment: .center) {
  330. Spacer()
  331. Group {
  332. Circle().fill(Color.loopGreen).frame(width: 8, height: 8)
  333. Text("BG")
  334. .font(.system(size: 12, weight: .bold)).foregroundColor(.loopGreen)
  335. }
  336. Group {
  337. Circle().fill(Color.insulin).frame(width: 8, height: 8)
  338. .padding(.leading, 8)
  339. Text("IOB")
  340. .font(.system(size: 12, weight: .bold)).foregroundColor(.insulin)
  341. }
  342. Group {
  343. Circle().fill(Color.zt).frame(width: 8, height: 8)
  344. .padding(.leading, 8)
  345. Text("ZT")
  346. .font(.system(size: 12, weight: .bold)).foregroundColor(.zt)
  347. }
  348. Spacer()
  349. loopView.padding(.top, 16)
  350. Spacer()
  351. Group {
  352. Circle().fill(Color.loopYellow).frame(width: 8, height: 8)
  353. Text("COB")
  354. .font(.system(size: 12, weight: .bold)).foregroundColor(.loopYellow)
  355. }
  356. Group {
  357. Circle().fill(Color.uam).frame(width: 8, height: 8)
  358. .padding(.leading, 8)
  359. Text("UAM")
  360. .font(.system(size: 12, weight: .bold)).foregroundColor(.uam)
  361. }
  362. if let eventualBG = state.eventualBG {
  363. Text(
  364. "⇢ " + numberFormatter.string(
  365. from: (state.units == .mmolL ? eventualBG.asMmolL : Decimal(eventualBG)) as NSNumber
  366. )!
  367. )
  368. .font(.system(size: 12, weight: .bold)).foregroundColor(.secondary)
  369. }
  370. Spacer()
  371. }
  372. .frame(maxWidth: .infinity)
  373. }
  374. }
  375. var timeInterval: some View {
  376. HStack(alignment: .center) {
  377. let saveButton = UXSettings(context: moc)
  378. ForEach(timeButtons) { button in
  379. Text(button.active ? NSLocalizedString(button.label, comment: "") : button.number).onTapGesture {
  380. let index = timeButtons.firstIndex(where: { $0.label == button.label }) ?? 0
  381. highlightButtons(index, onAppear: false)
  382. saveButton.hours = button.hours
  383. saveButton.date = Date.now
  384. try? moc.save()
  385. state.hours = button.hours
  386. }
  387. .foregroundStyle(button.active ? (colorScheme == .dark ? Color.white : Color.black).opacity(0.9) : .secondary)
  388. .frame(maxHeight: 30).padding(.horizontal, 8)
  389. .background(
  390. button.active ?
  391. // RGB(30, 60, 95)
  392. (
  393. colorScheme == .dark ? Color(red: 0.1176470588, green: 0.2352941176, blue: 0.3725490196) :
  394. Color.white
  395. ) :
  396. Color
  397. .clear
  398. )
  399. .cornerRadius(20)
  400. }
  401. }
  402. .shadow(
  403. color: colorScheme == .dark ? Color(
  404. red: 0.02745098039,
  405. green: 0.1098039216,
  406. blue: 0.1411764706
  407. ) : Color
  408. .black.opacity(0.33),
  409. radius: 3
  410. )
  411. .font(buttonFont)
  412. }
  413. var mainChart: some View {
  414. ZStack {
  415. if state.animatedBackground {
  416. SpriteView(scene: spriteScene, options: [.allowsTransparency])
  417. .ignoresSafeArea()
  418. .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
  419. }
  420. // MainChartView(
  421. // glucose: $state.glucose,
  422. // isManual: $state.isManual,
  423. // suggestion: $state.suggestion,
  424. // tempBasals: $state.tempBasals,
  425. // boluses: $state.boluses,
  426. // suspensions: $state.suspensions,
  427. // announcement: $state.announcement,
  428. // hours: .constant(state.filteredHours),
  429. // maxBasal: $state.maxBasal,
  430. // autotunedBasalProfile: $state.autotunedBasalProfile,
  431. // basalProfile: $state.basalProfile,
  432. // tempTargets: $state.tempTargets,
  433. // carbs: $state.carbs,
  434. // timerDate: $state.timerDate,
  435. // units: $state.units,
  436. // smooth: $state.smooth,
  437. // highGlucose: $state.highGlucose,
  438. // lowGlucose: $state.lowGlucose,
  439. // screenHours: $state.hours,
  440. // displayXgridLines: $state.displayXgridLines,
  441. // displayYgridLines: $state.displayYgridLines,
  442. // thresholdLines: $state.thresholdLines
  443. // )
  444. // MARK: SWIFT CHARTS
  445. MainChartView2(
  446. glucose: $state.glucose,
  447. isManual: $state.isManual,
  448. suggestion: $state.suggestion,
  449. tempBasals: $state.tempBasals,
  450. boluses: $state.boluses,
  451. suspensions: $state.suspensions,
  452. announcement: $state.announcement,
  453. hours: .constant(state.filteredHours),
  454. maxBasal: $state.maxBasal,
  455. autotunedBasalProfile: $state.autotunedBasalProfile,
  456. basalProfile: $state.basalProfile,
  457. tempTargets: $state.tempTargets,
  458. carbs: $state.carbs,
  459. timerDate: $state.timerDate,
  460. units: $state.units,
  461. smooth: $state.smooth,
  462. highGlucose: $state.highGlucose,
  463. lowGlucose: $state.lowGlucose,
  464. screenHours: $state.hours,
  465. displayXgridLines: $state.displayXgridLines,
  466. displayYgridLines: $state.displayYgridLines,
  467. thresholdLines: $state.thresholdLines
  468. )
  469. }
  470. .padding(.bottom)
  471. .modal(for: .dataTable, from: self)
  472. }
  473. private func selectedProfile() -> (name: String, isOn: Bool) {
  474. var profileString = ""
  475. var display: Bool = false
  476. let duration = (fetchedPercent.first?.duration ?? 0) as Decimal
  477. let indefinite = fetchedPercent.first?.indefinite ?? false
  478. let addedMinutes = Int(duration)
  479. let date = fetchedPercent.first?.date ?? Date()
  480. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) > Date() || indefinite {
  481. display.toggle()
  482. }
  483. if fetchedPercent.first?.enabled ?? false, !(fetchedPercent.first?.isPreset ?? false), display {
  484. profileString = NSLocalizedString("Custom Profile", comment: "Custom but unsaved Profile")
  485. } else if !(fetchedPercent.first?.enabled ?? false) || !display {
  486. profileString = NSLocalizedString("Normal Profile", comment: "Your normal Profile. Use a short string")
  487. } else {
  488. let id_ = fetchedPercent.first?.id ?? ""
  489. let profile = fetchedProfiles.filter({ $0.id == id_ }).first
  490. if profile != nil {
  491. profileString = profile?.name?.description ?? ""
  492. }
  493. }
  494. return (name: profileString, isOn: display)
  495. }
  496. func highlightButtons(_ int: Int?, onAppear: Bool) {
  497. var index = 0
  498. if let integer = int, !onAppear {
  499. repeat {
  500. if index == integer {
  501. timeButtons[index].active = true
  502. } else {
  503. timeButtons[index].active = false
  504. }
  505. index += 1
  506. } while index < timeButtons.count
  507. } else if onAppear {
  508. let i = timeButtons.firstIndex(where: { $0.hours == (fetchedSettings.first?.hours ?? 6) }) ?? 2
  509. index = 0
  510. repeat {
  511. if index == i {
  512. timeButtons[index].active = true
  513. } else {
  514. timeButtons[index].active = false
  515. }
  516. index += 1
  517. } while index < timeButtons.count
  518. }
  519. }
  520. @ViewBuilder private func bottomPanel(_: GeometryProxy) -> some View {
  521. let colorRectangle: Color = colorScheme == .dark ? Color.black.opacity(0.8) : Color.white
  522. let colorIcon: Color = (colorScheme == .dark ? Color.white : Color.black).opacity(0.9)
  523. ZStack {
  524. Rectangle()
  525. .fill(colorRectangle)
  526. .frame(height: UIScreen.main.bounds.height / 13)
  527. .cornerRadius(15)
  528. .shadow(
  529. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) : Color
  530. .black.opacity(0.33),
  531. radius: 3
  532. )
  533. .padding([.leading, .trailing], 10)
  534. HStack {
  535. Button { state.showModal(for: .addCarbs(editMode: false, override: false)) }
  536. label: {
  537. ZStack(alignment: Alignment(horizontal: .trailing, vertical: .bottom)) {
  538. Image("carbs")
  539. .renderingMode(.template)
  540. .resizable()
  541. .frame(width: 24, height: 24)
  542. .foregroundColor(colorIcon)
  543. .padding(8)
  544. if let carbsReq = state.carbsRequired {
  545. Text(numberFormatter.string(from: carbsReq as NSNumber)!)
  546. .font(.caption)
  547. .foregroundColor(.white)
  548. .padding(4)
  549. .background(Capsule().fill(Color.red))
  550. }
  551. }
  552. }.buttonStyle(.borderless)
  553. Spacer()
  554. Button { state.showModal(for: .addTempTarget) }
  555. label: {
  556. Image("target")
  557. .renderingMode(.template)
  558. .resizable()
  559. .frame(width: 24, height: 24)
  560. .padding(8)
  561. }
  562. .foregroundColor(colorIcon)
  563. .buttonStyle(.borderless)
  564. Spacer()
  565. Button {
  566. state.showModal(for: .bolus(
  567. waitForSuggestion: true,
  568. fetch: false
  569. ))
  570. }
  571. label: {
  572. Image("bolus")
  573. .renderingMode(.template)
  574. .resizable()
  575. .frame(width: 24, height: 24)
  576. .padding(8)
  577. }
  578. .foregroundColor(colorIcon)
  579. .buttonStyle(.borderless)
  580. Spacer()
  581. if state.allowManualTemp {
  582. Button { state.showModal(for: .manualTempBasal) }
  583. label: {
  584. Image("bolus1")
  585. .renderingMode(.template)
  586. .resizable()
  587. .frame(width: 24, height: 24)
  588. .padding(8)
  589. }
  590. .foregroundColor(colorIcon)
  591. .buttonStyle(.borderless)
  592. Spacer()
  593. }
  594. // MARK: CANCEL OF PROFILE HAS TO BE IMPLEMENTED
  595. // MAYBE WITH A SMALL INDICATOR AT THE SYMBOL
  596. Button {
  597. state.showModal(for: .overrideProfilesConfig)
  598. } label: {
  599. Image(systemName: "person")
  600. .renderingMode(.template)
  601. .resizable()
  602. .frame(width: 24, height: 24)
  603. .padding(8)
  604. }
  605. .foregroundColor(colorIcon)
  606. .buttonStyle(.borderless)
  607. Spacer()
  608. Button { state.showModal(for: .statistics)
  609. }
  610. label: {
  611. Image(systemName: "chart.xyaxis.line")
  612. .renderingMode(.template)
  613. .resizable()
  614. .frame(width: 24, height: 24)
  615. .padding(8)
  616. }
  617. .foregroundColor(colorIcon)
  618. .buttonStyle(.borderless)
  619. Spacer()
  620. Button { state.showModal(for: .settings) }
  621. label: {
  622. Image("settings1")
  623. .renderingMode(.template)
  624. .resizable()
  625. .frame(width: 24, height: 24)
  626. .padding(8)
  627. }
  628. .foregroundColor(colorIcon)
  629. .buttonStyle(.borderless)
  630. }
  631. .padding(.horizontal, 24)
  632. .padding(.bottom, 16)
  633. }
  634. }
  635. var body: some View {
  636. let colorBackground = colorScheme == .dark ? LinearGradient(
  637. gradient: Gradient(colors: [
  638. // RGB(3, 15, 28)
  639. Color(red: 0.011, green: 0.058, blue: 0.109),
  640. Color(red: 0.011, green: 0.058, blue: 0.109),
  641. // RGB(1, 3, 8)
  642. Color(red: 0.003, green: 0.011, blue: 0.031)
  643. ]),
  644. startPoint: .bottom,
  645. endPoint: .top
  646. )
  647. :
  648. LinearGradient(gradient: Gradient(colors: [Color.gray.opacity(0.1)]), startPoint: .top, endPoint: .bottom)
  649. let colourChart: Color = colorScheme == .dark ? .black.opacity(0.8) : .white
  650. GeometryReader { geo in
  651. VStack(spacing: 0) {
  652. Spacer()
  653. // ZStack {
  654. glucoseView.padding(.top, 75)
  655. // loopView
  656. // /// circles width is 110, loops width is 35 -> (110/2) - (35/2) = 55 - 17.5 = 37.5
  657. // .offset(x: UIScreen.main.bounds.width * 0.43, y: -37.5)
  658. // .padding(.trailing, 10)
  659. // }
  660. // .padding(.top, 75)
  661. Spacer()
  662. header(geo)
  663. .padding(.top, 15)
  664. .padding(.horizontal, 10)
  665. Spacer()
  666. infoPanel
  667. .padding(.horizontal, 10)
  668. RoundedRectangle(cornerRadius: 15)
  669. .fill(colourChart)
  670. .overlay(mainChart)
  671. .clipShape(RoundedRectangle(cornerRadius: 15))
  672. .shadow(
  673. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  674. Color.black.opacity(0.33),
  675. radius: 3
  676. )
  677. .padding(.horizontal, 10)
  678. .frame(maxHeight: UIScreen.main.bounds.height / 2.2)
  679. Spacer()
  680. timeInterval
  681. Spacer()
  682. bottomPanel(geo)
  683. }
  684. .background(colorBackground)
  685. .edgesIgnoringSafeArea(.all)
  686. }
  687. .onAppear(perform: configureView)
  688. .navigationTitle("Home")
  689. .navigationBarHidden(true)
  690. .ignoresSafeArea(.keyboard)
  691. .popup(isPresented: isStatusPopupPresented, alignment: .top, direction: .top) {
  692. popup
  693. .padding()
  694. .background(
  695. RoundedRectangle(cornerRadius: 8, style: .continuous)
  696. .fill(Color(UIColor.darkGray))
  697. )
  698. .onTapGesture {
  699. isStatusPopupPresented = false
  700. }
  701. .gesture(
  702. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  703. .onEnded { value in
  704. if value.translation.height < 0 {
  705. isStatusPopupPresented = false
  706. }
  707. }
  708. )
  709. }
  710. }
  711. private var popup: some View {
  712. VStack(alignment: .leading, spacing: 4) {
  713. Text(state.statusTitle).font(.headline).foregroundColor(.white)
  714. .padding(.bottom, 4)
  715. if let suggestion = state.suggestion {
  716. TagCloudView(tags: suggestion.reasonParts).animation(.none, value: false)
  717. Text(suggestion.reasonConclusion.capitalizingFirstLetter()).font(.caption).foregroundColor(.white)
  718. } else {
  719. Text("No sugestion found").font(.body).foregroundColor(.white)
  720. }
  721. if let errorMessage = state.errorMessage, let date = state.errorDate {
  722. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  723. .foregroundColor(.white)
  724. .font(.headline)
  725. .padding(.bottom, 4)
  726. .padding(.top, 8)
  727. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  728. } else if let suggestion = state.suggestion, (suggestion.bg ?? 100) == 400 {
  729. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  730. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  731. }
  732. }
  733. }
  734. }
  735. }