HomeRootView.swift 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. import CoreData
  2. import SpriteKit
  3. import SwiftDate
  4. import SwiftUI
  5. import Swinject
  6. struct TimePicker: Identifiable {
  7. var active: Bool
  8. let hours: Int16
  9. var id: String { hours.description }
  10. }
  11. extension Home {
  12. struct RootView: BaseView {
  13. let resolver: Resolver
  14. let safeAreaSize: CGFloat = 0.08
  15. @Environment(\.managedObjectContext) var moc
  16. @Environment(\.colorScheme) var colorScheme
  17. @Environment(AppState.self) var appState
  18. @State var state = StateModel()
  19. @State var settingsPath = NavigationPath()
  20. @State var isStatusPopupPresented = false
  21. @State var showCancelAlert = false
  22. @State var showCancelConfirmDialog = false
  23. @State var isConfirmStopOverrideShown = false
  24. @State var isConfirmStopOverridePresented = false
  25. @State var isConfirmStopTempTargetShown = false
  26. @State var isMenuPresented = false
  27. @State var showTreatments = false
  28. @State var selectedTab: Int = 0
  29. @State var showPumpSelection: Bool = false
  30. @State var showCGMSelection: Bool = false
  31. @State var notificationsDisabled = false
  32. @State var timeButtons: [TimePicker] = [
  33. TimePicker(active: false, hours: 4),
  34. TimePicker(active: false, hours: 6),
  35. TimePicker(active: false, hours: 12),
  36. TimePicker(active: false, hours: 24)
  37. ]
  38. @FetchRequest(fetchRequest: OverrideStored.fetch(
  39. NSPredicate.lastActiveOverride,
  40. ascending: false,
  41. fetchLimit: 1
  42. )) var latestOverride: FetchedResults<OverrideStored>
  43. @FetchRequest(fetchRequest: TempTargetStored.fetch(
  44. NSPredicate.lastActiveTempTarget,
  45. ascending: false,
  46. fetchLimit: 1
  47. )) var latestTempTarget: FetchedResults<TempTargetStored>
  48. var bolusProgressFormatter: NumberFormatter {
  49. let formatter = NumberFormatter()
  50. formatter.numberStyle = .decimal
  51. formatter.minimum = 0
  52. formatter.maximumFractionDigits = state.settingsManager.preferences.bolusIncrement > 0.05 ? 1 : 2
  53. formatter.minimumFractionDigits = state.settingsManager.preferences.bolusIncrement > 0.05 ? 1 : 2
  54. formatter.allowsFloats = true
  55. formatter.roundingIncrement = Double(state.settingsManager.preferences.bolusIncrement) as NSNumber
  56. return formatter
  57. }
  58. private var fetchedTargetFormatter: NumberFormatter {
  59. let formatter = NumberFormatter()
  60. formatter.numberStyle = .decimal
  61. if state.units == .mmolL {
  62. formatter.maximumFractionDigits = 1
  63. } else { formatter.maximumFractionDigits = 0 }
  64. return formatter
  65. }
  66. private var historySFSymbol: String {
  67. if #available(iOS 17.0, *) {
  68. return "book.pages"
  69. } else {
  70. return "book"
  71. }
  72. }
  73. @ViewBuilder func pumpTimezoneView(_ badgeImage: UIImage, _ badgeColor: Color) -> some View {
  74. HStack {
  75. Image(uiImage: badgeImage.withRenderingMode(.alwaysTemplate))
  76. .font(.system(size: 14))
  77. .colorMultiply(badgeColor)
  78. Text(String(localized: "Time Change Detected", comment: ""))
  79. .bold()
  80. .font(.system(size: 14))
  81. .foregroundStyle(badgeColor)
  82. }
  83. .onTapGesture {
  84. if state.pumpDisplayState != nil {
  85. // sends user to pump settings
  86. state.shouldDisplayPumpSetupSheet.toggle()
  87. }
  88. }
  89. .frame(maxWidth: .infinity, alignment: .center)
  90. .padding(.vertical, 5)
  91. .padding(.horizontal, 10)
  92. .overlay(
  93. Capsule()
  94. .stroke(badgeColor.opacity(0.4), lineWidth: 2)
  95. )
  96. }
  97. var cgmSelectionButtons: some View {
  98. ForEach(cgmOptions, id: \.name) { option in
  99. if let cgm = state.listOfCGM.first(where: option.predicate) {
  100. Button(option.name) {
  101. state.addCGM(cgm: cgm)
  102. }
  103. }
  104. }
  105. }
  106. var glucoseView: some View {
  107. CurrentGlucoseView(
  108. timerDate: state.timerDate,
  109. units: state.units,
  110. alarm: state.alarm,
  111. lowGlucose: state.lowGlucose,
  112. highGlucose: state.highGlucose,
  113. cgmAvailable: state.cgmAvailable,
  114. currentGlucoseTarget: state.currentGlucoseTarget,
  115. glucoseColorScheme: state.glucoseColorScheme,
  116. glucose: state.latestTwoGlucoseValues
  117. ).scaleEffect(0.9)
  118. .onTapGesture {
  119. if !state.cgmAvailable {
  120. showCGMSelection.toggle()
  121. } else {
  122. state.shouldDisplayCGMSetupSheet.toggle()
  123. }
  124. }
  125. .onLongPressGesture {
  126. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  127. impactHeavy.impactOccurred()
  128. state.showModal(for: .snooze)
  129. }
  130. }
  131. var pumpView: some View {
  132. PumpView(
  133. reservoir: state.reservoir,
  134. name: state.pumpName,
  135. expiresAtDate: state.pumpExpiresAtDate,
  136. timerDate: state.timerDate,
  137. pumpStatusHighlightMessage: state.pumpStatusHighlightMessage,
  138. battery: state.batteryFromPersistence
  139. )
  140. .onTapGesture {
  141. if state.pumpDisplayState == nil {
  142. // shows user confirmation dialog with pump model choices, then proceeds to setup
  143. showPumpSelection.toggle()
  144. } else {
  145. // sends user to pump settings
  146. state.shouldDisplayPumpSetupSheet.toggle()
  147. }
  148. }
  149. }
  150. var tempBasalString: String? {
  151. guard let lastTempBasal = state.tempBasals.last?.tempBasal, let tempRate = lastTempBasal.rate else {
  152. return nil
  153. }
  154. let rateString = Formatter.decimalFormatterWithTwoFractionDigits.string(from: tempRate as NSNumber) ?? "0"
  155. var manualBasalString = ""
  156. if let apsManager = state.apsManager, apsManager.isManualTempBasal {
  157. manualBasalString = String(
  158. localized:
  159. " - Manual Basal ⚠️",
  160. comment: "Manual Temp basal"
  161. )
  162. }
  163. return rateString + String(localized: " U/hr", comment: "Unit per hour with space") + manualBasalString
  164. }
  165. var overrideString: String? {
  166. guard let latestOverride = latestOverride.first else {
  167. return nil
  168. }
  169. let percent = latestOverride.percentage
  170. let percentString = percent == 100 ? "" : "\(percent.formatted(.number)) %"
  171. let unit = state.units
  172. var target = (latestOverride.target ?? 100) as Decimal
  173. target = unit == .mmolL ? target.asMmolL : target
  174. var targetString = target == 0 ? "" : (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " + unit
  175. .rawValue
  176. if tempTargetString != nil {
  177. targetString = ""
  178. }
  179. let duration = latestOverride.duration ?? 0
  180. let addedMinutes = Int(truncating: duration)
  181. let date = latestOverride.date ?? Date()
  182. let newDuration = max(
  183. Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes),
  184. 0
  185. )
  186. let indefinite = latestOverride.indefinite
  187. var durationString = ""
  188. if !indefinite {
  189. if newDuration >= 1 {
  190. durationString = formatHrMin(Int(newDuration))
  191. } else if newDuration > 0 {
  192. durationString = "\(Int(newDuration * 60)) s"
  193. } else {
  194. /// Do not show the Override anymore
  195. Task {
  196. guard let objectID = self.latestOverride.first?.objectID else { return }
  197. await state.cancelOverride(withID: objectID)
  198. }
  199. }
  200. }
  201. let smbScheduleString = latestOverride
  202. .smbIsScheduledOff && ((latestOverride.start?.stringValue ?? "") != (latestOverride.end?.stringValue ?? ""))
  203. ? " \(formatTimeRange(start: latestOverride.start?.stringValue, end: latestOverride.end?.stringValue))"
  204. : ""
  205. let smbToggleString = latestOverride.smbIsOff || latestOverride
  206. .smbIsScheduledOff ? "SMBs Off\(smbScheduleString)" : ""
  207. let components = [durationString, percentString, targetString, smbToggleString].filter { !$0.isEmpty }
  208. return components.isEmpty ? nil : components.joined(separator: ", ")
  209. }
  210. var tempTargetString: String? {
  211. guard let latestTempTarget = latestTempTarget.first else {
  212. return nil
  213. }
  214. let duration = latestTempTarget.duration
  215. let addedMinutes = Int(truncating: duration ?? 0)
  216. let date = latestTempTarget.date ?? Date()
  217. let newDuration = max(
  218. Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes),
  219. 0
  220. )
  221. var durationString = ""
  222. var percentageString = ""
  223. var target = (latestTempTarget.target ?? 100) as Decimal
  224. var halfBasalTarget: Decimal = 160
  225. if latestTempTarget.halfBasalTarget != nil {
  226. halfBasalTarget = latestTempTarget.halfBasalTarget! as Decimal
  227. } else { halfBasalTarget = state.settingHalfBasalTarget }
  228. var showPercentage = false
  229. if target > 100, state.isExerciseModeActive || state.highTTraisesSens { showPercentage = true }
  230. if target < 100, state.lowTTlowersSens, state.autosensMax > 1 { showPercentage = true }
  231. if showPercentage {
  232. percentageString =
  233. " \(state.computeAdjustedPercentage(halfBasalTargetValue: halfBasalTarget, tempTargetValue: target))%" }
  234. target = state.units == .mmolL ? target.asMmolL : target
  235. let targetString = target == 0 ? "" : (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " +
  236. state.units.rawValue + percentageString
  237. if newDuration >= 1 {
  238. durationString =
  239. "\(newDuration.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) min"
  240. } else if newDuration > 0 {
  241. durationString =
  242. "\((newDuration * 60).formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) s"
  243. } else {
  244. /// Do not show the Temp Target anymore
  245. Task {
  246. guard let objectID = self.latestTempTarget.first?.objectID else { return }
  247. await state.cancelTempTarget(withID: objectID)
  248. }
  249. }
  250. let components = [targetString, durationString].filter { !$0.isEmpty }
  251. return components.isEmpty ? nil : components.joined(separator: ", ")
  252. }
  253. var timeIntervalButtons: some View {
  254. let buttonColor = (colorScheme == .dark ? Color.white : Color.black).opacity(0.8)
  255. return HStack(alignment: .center) {
  256. ForEach(timeButtons) { button in
  257. Button(action: {
  258. state.hours = button.hours
  259. }) {
  260. Group {
  261. if button.active {
  262. Text(
  263. button.hours.description + "\u{00A0}" +
  264. String(localized: "h", comment: "h")
  265. )
  266. } else {
  267. Text(button.hours.description)
  268. }
  269. }
  270. .font(.footnote)
  271. .fontWeight(button.active ? .semibold : .regular)
  272. .padding(.vertical, 5)
  273. .padding(.horizontal, 10)
  274. .foregroundColor(
  275. button
  276. .active ? (colorScheme == .dark ? Color.bgDarkerDarkBlue : Color.white) : buttonColor
  277. )
  278. .background(button.active ? buttonColor.opacity(colorScheme == .dark ? 1 : 0.8) : Color.clear)
  279. .clipShape(Capsule())
  280. .overlay(
  281. Capsule()
  282. .stroke(button.active ? buttonColor.opacity(0.4) : Color.clear, lineWidth: 2)
  283. )
  284. }
  285. }
  286. }
  287. }
  288. var statsIconString: String {
  289. if #available(iOS 18, *) {
  290. return "chart.line.text.clipboard"
  291. } else {
  292. return "list.clipboard"
  293. }
  294. }
  295. @ViewBuilder private func tappableButton(
  296. buttonColor: Color,
  297. label: String,
  298. iconString: String,
  299. action: @escaping () -> Void
  300. ) -> some View {
  301. Button(action: {
  302. action()
  303. }) {
  304. HStack {
  305. Image(systemName: iconString)
  306. Text(label)
  307. }
  308. .font(.footnote)
  309. .padding(.vertical, 5)
  310. .padding(.horizontal, 10)
  311. .foregroundStyle(buttonColor)
  312. .overlay(
  313. Capsule()
  314. .stroke(buttonColor.opacity(0.4), lineWidth: 2)
  315. )
  316. }
  317. }
  318. @ViewBuilder func mainChart(geo: GeometryProxy) -> some View {
  319. ZStack {
  320. MainChartView(
  321. geo: geo,
  322. safeAreaSize: notificationsDisabled == true ? safeAreaSize : 0,
  323. units: state.units,
  324. hours: state.filteredHours,
  325. highGlucose: state.highGlucose,
  326. lowGlucose: state.lowGlucose,
  327. currentGlucoseTarget: state.currentGlucoseTarget,
  328. glucoseColorScheme: state.glucoseColorScheme,
  329. screenHours: state.hours,
  330. displayXgridLines: state.displayXgridLines,
  331. displayYgridLines: state.displayYgridLines,
  332. thresholdLines: state.thresholdLines,
  333. state: state
  334. )
  335. }
  336. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: nil))
  337. }
  338. func highlightButtons() {
  339. for i in 0 ..< timeButtons.count {
  340. timeButtons[i].active = timeButtons[i].hours == state.hours
  341. }
  342. }
  343. @ViewBuilder func rightHeaderPanel(_: GeometryProxy) -> some View {
  344. VStack(alignment: .leading, spacing: 20) {
  345. /// Loop view at bottomLeading
  346. LoopView(
  347. closedLoop: state.closedLoop,
  348. timerDate: state.timerDate,
  349. isLooping: state.isLooping,
  350. lastLoopDate: state.lastLoopDate,
  351. manualTempBasal: state.manualTempBasal,
  352. determination: state.determinationsFromPersistence
  353. )
  354. .onTapGesture {
  355. state.isLoopStatusPresented = true
  356. }
  357. .onLongPressGesture {
  358. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  359. impactHeavy.impactOccurred()
  360. state.runLoop()
  361. }
  362. /// eventualBG string at bottomTrailing
  363. if let eventualBG = state.enactedAndNonEnactedDeterminations.first?.eventualBG {
  364. let eventualGlucose = eventualBG as Decimal
  365. HStack {
  366. Image(systemName: "arrow.right.circle")
  367. .font(.callout)
  368. .fontWeight(.bold)
  369. Text(state.units == .mgdL ? eventualGlucose.description : eventualGlucose.formattedAsMmolL)
  370. .font(.callout)
  371. .fontWeight(.bold)
  372. .fontDesign(.rounded)
  373. }
  374. // aligns the evBG icon exactly with the first pixel of loop status icon
  375. .padding(.leading, 12)
  376. } else {
  377. HStack {
  378. Image(systemName: "arrow.right.circle")
  379. .font(.callout).fontWeight(.bold)
  380. Text("--")
  381. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  382. }
  383. }
  384. }
  385. }
  386. @ViewBuilder func mealPanel(_: GeometryProxy) -> some View {
  387. HStack {
  388. HStack {
  389. Image(systemName: "syringe.fill")
  390. .font(.callout)
  391. .foregroundColor(Color.insulin)
  392. Text(
  393. (
  394. Formatter.decimalFormatterWithTwoFractionDigits
  395. .string(from: (state.enactedAndNonEnactedDeterminations.first?.iob ?? 0) as NSNumber) ?? "0"
  396. ) +
  397. String(localized: " U", comment: "Insulin unit")
  398. )
  399. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  400. }
  401. Spacer()
  402. HStack {
  403. Image(systemName: "fork.knife")
  404. .font(.callout)
  405. .foregroundColor(.loopYellow)
  406. Text(
  407. (
  408. Formatter.decimalFormatterWithTwoFractionDigits.string(
  409. from: NSNumber(value: state.enactedAndNonEnactedDeterminations.first?.cob ?? 0)
  410. ) ?? "0"
  411. ) +
  412. String(localized: " g", comment: "gram of carbs")
  413. )
  414. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  415. }
  416. Spacer()
  417. if state.maxIOB == 0.0 {
  418. HStack {
  419. Image(systemName: "exclamationmark.circle.fill")
  420. Text("MaxIOB: 0 U")
  421. }.bold()
  422. .foregroundStyle(Color.red)
  423. .font(.callout)
  424. } else {
  425. HStack {
  426. if state.pumpSuspended {
  427. Text("Pump suspended")
  428. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  429. .foregroundColor(.loopGray)
  430. } else if let tempBasalString = tempBasalString {
  431. Image(systemName: "drop.circle")
  432. .font(.callout)
  433. .foregroundColor(.insulinTintColor)
  434. if tempBasalString.count > 5 {
  435. Text(tempBasalString)
  436. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  437. .lineLimit(1)
  438. .minimumScaleFactor(0.85)
  439. .truncationMode(.tail)
  440. .allowsTightening(true)
  441. } else {
  442. // Short strings can just display normally
  443. Text(tempBasalString).font(.callout).fontWeight(.bold).fontDesign(.rounded)
  444. }
  445. } else {
  446. Image(systemName: "drop.circle")
  447. .font(.callout)
  448. .foregroundColor(.insulinTintColor)
  449. Text("No Data")
  450. .font(.callout).fontWeight(.bold).fontDesign(.rounded)
  451. }
  452. }
  453. }
  454. }.padding(.horizontal)
  455. }
  456. @ViewBuilder func adjustmentsOverrideView(_ overrideString: String) -> some View {
  457. Group {
  458. Image(systemName: "clock.arrow.2.circlepath")
  459. .font(.title2)
  460. .foregroundStyle(Color.primary, Color.purple)
  461. VStack(alignment: .leading) {
  462. Text(latestOverride.first?.name ?? String(localized: "Custom Override"))
  463. .font(.subheadline)
  464. .frame(alignment: .leading)
  465. Text(overrideString)
  466. .font(.caption)
  467. }
  468. }
  469. .onTapGesture {
  470. selectedTab = 2
  471. }
  472. }
  473. @ViewBuilder func adjustmentsTempTargetView(_ tempTargetString: String) -> some View {
  474. Group {
  475. Image(systemName: "target")
  476. .font(.title2)
  477. .foregroundStyle(Color.loopGreen)
  478. VStack(alignment: .leading) {
  479. Text(latestTempTarget.first?.name ?? String(localized: "Temp Target"))
  480. .font(.subheadline)
  481. Text(tempTargetString)
  482. .font(.caption)
  483. }
  484. }
  485. .onTapGesture {
  486. selectedTab = 2
  487. }
  488. }
  489. @ViewBuilder func adjustmentsCancelView(_ cancelAction: @escaping () -> Void) -> some View {
  490. Image(systemName: "xmark.app")
  491. .font(.title)
  492. .onTapGesture {
  493. cancelAction()
  494. }
  495. }
  496. @ViewBuilder func adjustmentsCancelTempTargetView() -> some View {
  497. Image(systemName: "xmark.app")
  498. .font(.title)
  499. .confirmationDialog(
  500. "Stop the Temp Target \"\(latestTempTarget.first?.name ?? "")\"?",
  501. isPresented: $isConfirmStopTempTargetShown,
  502. titleVisibility: .visible
  503. ) {
  504. Button("Stop", role: .destructive) {
  505. Task {
  506. guard let objectID = latestTempTarget.first?.objectID else { return }
  507. await state.cancelTempTarget(withID: objectID)
  508. }
  509. }
  510. Button("Cancel", role: .cancel) {}
  511. }
  512. .padding(.trailing, 8)
  513. .onTapGesture {
  514. if !latestTempTarget.isEmpty {
  515. isConfirmStopTempTargetShown = true
  516. }
  517. }
  518. }
  519. @ViewBuilder func adjustmentsCancelOverrideView() -> some View {
  520. Image(systemName: "xmark.app")
  521. .font(.title)
  522. .confirmationDialog(
  523. "Stop the Override \"\(latestOverride.first?.name ?? "")\"?",
  524. isPresented: $isConfirmStopOverridePresented,
  525. titleVisibility: .visible
  526. ) {
  527. Button("Stop", role: .destructive) {
  528. Task {
  529. guard let objectID = latestOverride.first?.objectID else { return }
  530. await state.cancelOverride(withID: objectID)
  531. }
  532. }
  533. Button("Cancel", role: .cancel) {}
  534. }
  535. .padding(.trailing, 8)
  536. .onTapGesture {
  537. if !latestOverride.isEmpty {
  538. isConfirmStopOverridePresented = true
  539. }
  540. }
  541. }
  542. @ViewBuilder func noActiveAdjustmentsView() -> some View {
  543. Group {
  544. VStack {
  545. Text("No Active Adjustment")
  546. .font(.subheadline)
  547. .frame(maxWidth: .infinity, alignment: .leading)
  548. Text("Profile at 100 %")
  549. .font(.caption)
  550. .frame(maxWidth: .infinity, alignment: .leading)
  551. }.padding(.leading, 10)
  552. Spacer()
  553. /// to ensure the same position....
  554. Image(systemName: "xmark.app")
  555. .font(.title)
  556. // clear color for the icon
  557. .foregroundStyle(Color.clear)
  558. }.onTapGesture {
  559. selectedTab = 2
  560. }
  561. }
  562. @ViewBuilder func adjustmentView(geo: GeometryProxy) -> some View {
  563. // let background = colorScheme == .dark ? Material.ultraThinMaterial.opacity(0.5) : Color.black.opacity(0.2)
  564. ZStack {
  565. /// rectangle as background
  566. RoundedRectangle(cornerRadius: 15)
  567. .fill(
  568. (overrideString != nil || tempTargetString != nil) ?
  569. (
  570. colorScheme == .dark ?
  571. Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) :
  572. Color.insulin.opacity(0.1)
  573. ) : Color.clear // Use clear and add the Material in the background
  574. )
  575. .background(colorScheme == .dark ? Color.chart.opacity(0.25) : Color.black.opacity(0.075))
  576. .clipShape(RoundedRectangle(cornerRadius: 15))
  577. .frame(height: geo.size.height * 0.08)
  578. .shadow(
  579. color: (overrideString != nil || tempTargetString != nil) ?
  580. (
  581. colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  582. Color.black.opacity(0.33)
  583. ) : Color.clear,
  584. radius: 3
  585. )
  586. HStack {
  587. if let overrideString = overrideString, let tempTargetString = tempTargetString {
  588. HStack {
  589. adjustmentsOverrideView(overrideString)
  590. Spacer()
  591. Divider()
  592. .frame(height: geo.size.height * 0.05)
  593. .padding(.horizontal, 2)
  594. adjustmentsTempTargetView(tempTargetString)
  595. Spacer()
  596. adjustmentsCancelView({
  597. if !latestTempTarget.isEmpty, !latestOverride.isEmpty {
  598. showCancelConfirmDialog = true
  599. } else if !latestOverride.isEmpty {
  600. showCancelAlert = true
  601. } else if !latestTempTarget.isEmpty {
  602. showCancelAlert = true
  603. }
  604. })
  605. }
  606. } else if let overrideString = overrideString {
  607. adjustmentsOverrideView(overrideString)
  608. Spacer()
  609. adjustmentsCancelOverrideView()
  610. } else if let tempTargetString = tempTargetString {
  611. HStack {
  612. adjustmentsTempTargetView(tempTargetString)
  613. Spacer()
  614. adjustmentsCancelTempTargetView()
  615. }
  616. } else {
  617. noActiveAdjustmentsView()
  618. }
  619. }.padding(.horizontal, 10)
  620. .confirmationDialog("Adjustment to Stop", isPresented: $showCancelConfirmDialog) {
  621. Button("Stop Override", role: .destructive) {
  622. Task {
  623. guard let objectID = latestOverride.first?.objectID else { return }
  624. await state.cancelOverride(withID: objectID)
  625. }
  626. }
  627. Button("Stop Temp Target", role: .destructive) {
  628. Task {
  629. guard let objectID = latestTempTarget.first?.objectID else { return }
  630. await state.cancelTempTarget(withID: objectID)
  631. }
  632. }
  633. Button("Stop All Adjustments", role: .destructive) {
  634. Task {
  635. guard let overrideObjectID = latestOverride.first?.objectID else { return }
  636. await state.cancelOverride(withID: overrideObjectID)
  637. guard let tempTargetObjectID = latestTempTarget.first?.objectID else { return }
  638. await state.cancelTempTarget(withID: tempTargetObjectID)
  639. }
  640. }
  641. } message: {
  642. Text("Select Adjustment")
  643. }
  644. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  645. }
  646. @ViewBuilder func bolusProgressBar(_ progress: Decimal) -> some View {
  647. GeometryReader { geo in
  648. RoundedRectangle(cornerRadius: 15)
  649. .frame(height: 6)
  650. .foregroundColor(.clear)
  651. .background(
  652. LinearGradient(colors: [
  653. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  654. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  655. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  656. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  657. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  658. ], startPoint: .leading, endPoint: .trailing)
  659. .mask(alignment: .leading) {
  660. RoundedRectangle(cornerRadius: 15)
  661. .frame(width: geo.size.width * CGFloat(progress))
  662. }
  663. )
  664. }
  665. }
  666. @ViewBuilder func bolusView(geo: GeometryProxy, _ progress: Decimal) -> some View {
  667. /// ensure that state.lastPumpBolus has a value, i.e. there is a last bolus done by the pump and not an external bolus
  668. /// - TRUE: show the pump bolus
  669. /// - FALSE: do not show a progress bar at all
  670. if let bolusTotal = state.lastPumpBolus?.bolus?.amount {
  671. let bolusFraction = progress * (bolusTotal as Decimal)
  672. let bolusString =
  673. (bolusProgressFormatter.string(from: bolusFraction as NSNumber) ?? "0")
  674. + String(localized: " of ", comment: "Bolus string partial message: 'x U of y U' in home view") +
  675. (Formatter.decimalFormatterWithTwoFractionDigits.string(from: bolusTotal as NSNumber) ?? "0")
  676. + String(localized: " U", comment: "Insulin unit")
  677. ZStack {
  678. /// rectangle as background
  679. RoundedRectangle(cornerRadius: 15)
  680. .fill(
  681. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color
  682. .insulin
  683. .opacity(0.2)
  684. )
  685. .clipShape(RoundedRectangle(cornerRadius: 15))
  686. .frame(height: geo.size.height * 0.08)
  687. .shadow(
  688. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  689. Color.black.opacity(0.33),
  690. radius: 3
  691. )
  692. /// actual bolus view
  693. HStack {
  694. Image(systemName: "cross.vial.fill")
  695. .font(.system(size: 25))
  696. Spacer()
  697. VStack {
  698. Text("Bolusing")
  699. .font(.subheadline)
  700. .frame(maxWidth: .infinity, alignment: .leading)
  701. Text(bolusString)
  702. .font(.caption)
  703. .frame(maxWidth: .infinity, alignment: .leading)
  704. }.padding(.leading, 5)
  705. Spacer()
  706. Button {
  707. state.showProgressView()
  708. state.cancelBolus()
  709. } label: {
  710. Image(systemName: "xmark.app")
  711. .font(.system(size: 25))
  712. }
  713. }.padding(.horizontal, 10)
  714. .padding(.trailing, 8)
  715. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  716. .overlay(alignment: .bottom) {
  717. // Use a geo-based offset here to position progress bar independent of device size
  718. let offset = geo.size.height * 0.0725
  719. bolusProgressBar(progress).padding(.horizontal, 18)
  720. .offset(y: offset)
  721. }.clipShape(RoundedRectangle(cornerRadius: 15))
  722. }
  723. }
  724. @ViewBuilder func alertSafetyNotificationsView(geo: GeometryProxy) -> some View {
  725. ZStack {
  726. /// rectangle as background
  727. RoundedRectangle(cornerRadius: 15)
  728. .fill(
  729. Color(
  730. red: 0.9,
  731. green: 0.133333333,
  732. blue: 0.2156862745
  733. )
  734. )
  735. .clipShape(RoundedRectangle(cornerRadius: 15))
  736. .frame(height: geo.size.height * safeAreaSize)
  737. .coordinateSpace(name: "alertSafetyNotificationsView")
  738. .shadow(
  739. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  740. Color.black.opacity(0.33),
  741. radius: 3
  742. )
  743. HStack {
  744. Spacer()
  745. VStack {
  746. Text("⚠️ Safety Notifications are OFF")
  747. .font(.headline)
  748. .fontWeight(.bold)
  749. .fontDesign(.rounded)
  750. .foregroundStyle(.white.gradient)
  751. .frame(maxWidth: .infinity, alignment: .leading)
  752. Text("Fix now by turning Notifications ON.")
  753. .font(.footnote)
  754. .fontDesign(.rounded)
  755. .foregroundStyle(.white.gradient)
  756. .frame(maxWidth: .infinity, alignment: .leading)
  757. }.padding(.leading, 5)
  758. Spacer()
  759. Image(systemName: "chevron.right").foregroundColor(.white)
  760. .font(.headline)
  761. }.padding(.horizontal, 10)
  762. .padding(.trailing, 8)
  763. .onTapGesture {
  764. UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
  765. }
  766. }.padding(.horizontal, 10)
  767. .padding(.top, 0)
  768. }
  769. @ViewBuilder func mainViewElements(_ geo: GeometryProxy) -> some View {
  770. VStack(spacing: 0) {
  771. ZStack {
  772. if let apsManager = state.apsManager, let bluetoothManager = apsManager.bluetoothManager,
  773. bluetoothManager.bluetoothAuthorization != .authorized
  774. {
  775. BluetoothRequiredView()
  776. } else {
  777. /// right panel with loop status and evBG
  778. HStack {
  779. Spacer()
  780. rightHeaderPanel(geo)
  781. }.padding(.trailing, 20)
  782. /// glucose bobble
  783. glucoseView
  784. /// left panel with pump related info
  785. HStack {
  786. pumpView
  787. Spacer()
  788. }.padding(.leading, 20)
  789. }
  790. }
  791. .padding(.top, 10)
  792. .safeAreaInset(edge: .top, spacing: 0) {
  793. if notificationsDisabled {
  794. alertSafetyNotificationsView(geo: geo)
  795. }
  796. if let badgeImage = state.pumpStatusBadgeImage, let badgeColor = state.pumpStatusBadgeColor {
  797. pumpTimezoneView(badgeImage, badgeColor)
  798. .padding(.horizontal, 20)
  799. }
  800. }
  801. mealPanel(geo).padding(.top, UIDevice.adjustPadding(min: nil, max: 30))
  802. .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 20))
  803. mainChart(geo: geo)
  804. HStack {
  805. tappableButton(
  806. buttonColor: (colorScheme == .dark ? Color.white : Color.black).opacity(0.8),
  807. label: String(localized: "Stats", comment: "Stats icon in main view"),
  808. iconString: statsIconString,
  809. action: { state.showModal(for: .statistics) }
  810. )
  811. Spacer()
  812. timeIntervalButtons.padding(.top, UIDevice.adjustPadding(min: 0, max: 10))
  813. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: 10))
  814. Spacer()
  815. tappableButton(
  816. buttonColor: (colorScheme == .dark ? Color.white : Color.black).opacity(0.8),
  817. label: String(localized: "Info", comment: "Info icon in main view"),
  818. iconString: "info",
  819. action: { state.isLegendPresented.toggle() }
  820. )
  821. }.padding([.horizontal, .bottom])
  822. if let progress = state.bolusProgress {
  823. bolusView(geo: geo, progress)
  824. .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  825. } else {
  826. adjustmentView(geo: geo).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  827. }
  828. }
  829. .background(appState.trioBackgroundColor(for: colorScheme))
  830. .onReceive(
  831. resolver.resolve(AlertPermissionsChecker.self)!.$notificationsDisabled,
  832. perform: {
  833. if notificationsDisabled != $0 {
  834. notificationsDisabled = $0
  835. if notificationsDisabled {
  836. debug(.default, "notificationsDisabled")
  837. }
  838. }
  839. }
  840. )
  841. }
  842. @ViewBuilder func mainView() -> some View {
  843. GeometryReader { geo in
  844. mainViewElements(geo)
  845. }
  846. .onChange(of: state.hours) {
  847. highlightButtons()
  848. }
  849. .onAppear {
  850. configureView {
  851. highlightButtons()
  852. }
  853. }
  854. .navigationTitle("Home")
  855. .navigationBarHidden(true)
  856. .ignoresSafeArea(.keyboard)
  857. .blur(radius: state.isLoopStatusPresented ? 3 : 0)
  858. .sheet(isPresented: $state.isLoopStatusPresented) {
  859. LoopStatusView(state: state)
  860. }
  861. .sheet(isPresented: $state.isLegendPresented) {
  862. ChartLegendView(state: state)
  863. }
  864. // PUMP RELATED
  865. .confirmationDialog("Pump Model", isPresented: $showPumpSelection) {
  866. Button("Medtronic") { state.addPump(.minimed) }
  867. Button("Omnipod Eros") { state.addPump(.omnipod) }
  868. Button("Omnipod DASH") { state.addPump(.omnipodBLE) }
  869. Button("Dana(RS/-i)") { state.addPump(.dana) }
  870. Button("Pump Simulator") { state.addPump(.simulator) }
  871. } message: { Text("Select Pump Model") }
  872. .sheet(isPresented: $state.shouldDisplayPumpSetupSheet) {
  873. if let pumpManager = state.provider.apsManager.pumpManager {
  874. PumpConfig.PumpSettingsView(
  875. pumpManager: pumpManager,
  876. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  877. completionDelegate: state,
  878. setupDelegate: state
  879. )
  880. } else {
  881. PumpConfig.PumpSetupView(
  882. pumpType: state.setupPumpType,
  883. pumpInitialSettings: PumpConfig.PumpInitialSettings.default,
  884. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  885. completionDelegate: state,
  886. setupDelegate: state
  887. )
  888. }
  889. }
  890. // CGM RELATED
  891. .confirmationDialog("CGM Model", isPresented: $showCGMSelection) {
  892. cgmSelectionButtons
  893. } message: {
  894. Text("Select CGM Model")
  895. }
  896. .sheet(isPresented: $state.shouldDisplayCGMSetupSheet) {
  897. switch state.cgmCurrent.type {
  898. case .enlite,
  899. .nightscout,
  900. .none,
  901. .simulator,
  902. .xdrip:
  903. CGMSettings.CustomCGMOptionsView(
  904. resolver: self.resolver,
  905. state: state.cgmStateModel,
  906. cgmCurrent: state.cgmCurrent,
  907. deleteCGM: state.deleteCGM
  908. )
  909. case .plugin:
  910. if let fetchGlucoseManager = state.fetchGlucoseManager,
  911. let cgmManager = fetchGlucoseManager.cgmManager,
  912. state.cgmCurrent.type == fetchGlucoseManager.cgmGlucoseSourceType,
  913. state.cgmCurrent.id == fetchGlucoseManager.cgmGlucosePluginId
  914. {
  915. CGMSettings.CGMSettingsView(
  916. cgmManager: cgmManager,
  917. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  918. unit: state.settingsManager.settings.units,
  919. completionDelegate: state
  920. )
  921. } else {
  922. CGMSettings.CGMSetupView(
  923. CGMType: state.cgmCurrent,
  924. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  925. unit: state.settingsManager.settings.units,
  926. completionDelegate: state,
  927. setupDelegate: state,
  928. pluginCGMManager: self.state.pluginCGMManager
  929. )
  930. }
  931. }
  932. }
  933. }
  934. @ViewBuilder func tabBar() -> some View {
  935. ZStack(alignment: .bottom) {
  936. TabView(selection: $selectedTab) {
  937. let carbsRequiredBadge: String? = {
  938. guard let carbsRequired = state.enactedAndNonEnactedDeterminations.first?.carbsRequired,
  939. state.showCarbsRequiredBadge
  940. else {
  941. return nil
  942. }
  943. let carbsRequiredDecimal = Decimal(carbsRequired)
  944. if carbsRequiredDecimal > state.settingsManager.settings.carbsRequiredThreshold {
  945. let numberAsNSNumber = NSDecimalNumber(decimal: carbsRequiredDecimal)
  946. return (Formatter.decimalFormatterWithTwoFractionDigits.string(from: numberAsNSNumber) ?? "") + " g"
  947. }
  948. return nil
  949. }()
  950. NavigationStack { mainView() }
  951. .tabItem { Label("Main", systemImage: "chart.xyaxis.line") }
  952. .badge(carbsRequiredBadge).tag(0)
  953. NavigationStack { DataTable.RootView(resolver: resolver) }
  954. .tabItem { Label("History", systemImage: historySFSymbol) }.tag(1)
  955. Spacer()
  956. NavigationStack { Adjustments.RootView(resolver: resolver) }
  957. .tabItem {
  958. Label(
  959. "Adjustments",
  960. systemImage: "slider.horizontal.2.gobackward"
  961. ) }.tag(2)
  962. NavigationStack(path: self.$settingsPath) {
  963. Settings.RootView(resolver: resolver) }
  964. .tabItem { Label(
  965. "Settings",
  966. systemImage: "gear"
  967. ) }.tag(3)
  968. }
  969. .tint(Color.tabBar)
  970. Button(
  971. action: {
  972. state.showModal(for: .treatmentView) },
  973. label: {
  974. Image(systemName: "plus.circle.fill")
  975. .font(.system(size: 40))
  976. .foregroundStyle(Color.tabBar)
  977. .padding(.vertical, 2)
  978. .padding(.horizontal, 24)
  979. }
  980. )
  981. }.ignoresSafeArea(.keyboard, edges: .bottom).blur(radius: state.waitForSuggestion ? 8 : 0)
  982. .onChange(of: selectedTab) {
  983. if !settingsPath.isEmpty {
  984. settingsPath = NavigationPath()
  985. }
  986. }
  987. }
  988. var body: some View {
  989. ZStack(alignment: .center) {
  990. tabBar()
  991. if state.waitForSuggestion {
  992. CustomProgressView(text: String(localized: "Updating IOB...", comment: "Progress text when updating IOB"))
  993. }
  994. }
  995. }
  996. }
  997. }
  998. extension UIDevice {
  999. public enum DeviceSize: CGFloat {
  1000. case smallDevice = 667 // Height for 4" iPhone SE
  1001. case largeDevice = 852 // Height for 6.1" iPhone 15 Pro
  1002. }
  1003. @usableFromInline static func adjustPadding(
  1004. min: CGFloat? = nil,
  1005. max: CGFloat? = nil
  1006. ) -> CGFloat? {
  1007. if UIScreen.screenHeight > UIDevice.DeviceSize.smallDevice.rawValue {
  1008. if UIScreen.screenHeight >= UIDevice.DeviceSize.largeDevice.rawValue {
  1009. return max
  1010. } else {
  1011. return min != nil ?
  1012. (max != nil ? max! * (UIScreen.screenHeight / UIDevice.DeviceSize.largeDevice.rawValue) : nil) : nil
  1013. }
  1014. } else {
  1015. return min
  1016. }
  1017. }
  1018. }
  1019. extension UIScreen {
  1020. static var screenHeight: CGFloat {
  1021. UIScreen.main.bounds.height
  1022. }
  1023. static var screenWidth: CGFloat {
  1024. UIScreen.main.bounds.width
  1025. }
  1026. }
  1027. /// Checks if the device is using a 24-hour time format.
  1028. func is24HourFormat() -> Bool {
  1029. let formatter = DateFormatter()
  1030. formatter.locale = Locale.current
  1031. formatter.dateStyle = .none
  1032. formatter.timeStyle = .short
  1033. let dateString = formatter.string(from: Date())
  1034. return !dateString.contains("AM") && !dateString.contains("PM")
  1035. }
  1036. /// Converts a duration in minutes to a formatted string (e.g., "1 h 30 m").
  1037. func formatHrMin(_ durationInMinutes: Int) -> String {
  1038. let hours = durationInMinutes / 60
  1039. let minutes = durationInMinutes % 60
  1040. switch (hours, minutes) {
  1041. case let (0, m):
  1042. return "\(m)\u{00A0}" + String(localized: "m", comment: "Abbreviation for Minutes")
  1043. case let (h, 0):
  1044. return "\(h)\u{00A0}" + String(localized: "h", comment: "h")
  1045. default:
  1046. return hours.description + "\u{00A0}" + String(localized: "h", comment: "h") + "\u{00A0}" + minutes
  1047. .description + "\u{00A0}" + String(localized: "m", comment: "Abbreviation for Minutes")
  1048. }
  1049. }
  1050. // Helper function to convert a start and end hour to either 24-hour or AM/PM format
  1051. func formatTimeRange(start: String?, end: String?) -> String {
  1052. guard let start = start, let end = end else {
  1053. return ""
  1054. }
  1055. // Check if the format is 24-hour or AM/PM
  1056. if is24HourFormat() {
  1057. // Return the original 24-hour format
  1058. return "\(start)-\(end)"
  1059. } else {
  1060. // Convert to AM/PM format using DateFormatter
  1061. let formatter = DateFormatter()
  1062. formatter.dateFormat = "HH"
  1063. if let startHour = Int(start), let endHour = Int(end) {
  1064. let startDate = Calendar.current.date(bySettingHour: startHour, minute: 0, second: 0, of: Date()) ?? Date()
  1065. let endDate = Calendar.current.date(bySettingHour: endHour, minute: 0, second: 0, of: Date()) ?? Date()
  1066. // Customize the format to "2p" or "2a"
  1067. formatter.dateFormat = "ha"
  1068. let startFormatted = formatter.string(from: startDate).lowercased().replacingOccurrences(of: "m", with: "")
  1069. let endFormatted = formatter.string(from: endDate).lowercased().replacingOccurrences(of: "m", with: "")
  1070. return "\(startFormatted)-\(endFormatted)"
  1071. } else {
  1072. return ""
  1073. }
  1074. }
  1075. }