HomeRootView.swift 50 KB

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