HomeRootView.swift 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370
  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. @State var state = StateModel()
  10. @State var isStatusPopupPresented = false
  11. @State var showCancelAlert = false
  12. @State var showCancelConfirmDialog = false
  13. @State var isConfirmStopOverrideShown = false
  14. @State var isConfirmStopOverridePresented = false
  15. @State var isConfirmStopTempTargetShown = false
  16. @State var isMenuPresented = false
  17. @State var showTreatments = false
  18. @State var selectedTab: Int = 0
  19. @State private var statusTitle: String = ""
  20. @State var showPumpSelection: Bool = false
  21. @State var notificationsDisabled = false
  22. @State var alertSafetyNotificationsViewHeight = 0
  23. struct Buttons: Identifiable {
  24. let label: String
  25. let number: String
  26. var active: Bool
  27. let hours: Int16
  28. var id: String { label }
  29. }
  30. @State var timeButtons: [Buttons] = [
  31. Buttons(label: "2 hours", number: "2", active: false, hours: 2),
  32. Buttons(label: "4 hours", number: "4", active: false, hours: 4),
  33. Buttons(label: "6 hours", number: "6", active: false, hours: 6),
  34. Buttons(label: "12 hours", number: "12", active: false, hours: 12),
  35. Buttons(label: "24 hours", number: "24", active: false, hours: 24)
  36. ]
  37. let buttonFont = Font.custom("TimeButtonFont", size: 14)
  38. @Environment(\.managedObjectContext) var moc
  39. @Environment(\.colorScheme) var colorScheme
  40. @FetchRequest(fetchRequest: OverrideStored.fetch(
  41. NSPredicate.lastActiveOverride,
  42. ascending: false,
  43. fetchLimit: 1
  44. )) var latestOverride: FetchedResults<OverrideStored>
  45. @FetchRequest(fetchRequest: TempTargetStored.fetch(
  46. NSPredicate.lastActiveTempTarget,
  47. ascending: false,
  48. fetchLimit: 1
  49. )) var latestTempTarget: FetchedResults<TempTargetStored>
  50. // TODO: end todo
  51. var bolusProgressFormatter: NumberFormatter {
  52. let formatter = NumberFormatter()
  53. formatter.numberStyle = .decimal
  54. formatter.minimum = 0
  55. formatter.maximumFractionDigits = state.settingsManager.preferences.bolusIncrement > 0.05 ? 1 : 2
  56. formatter.minimumFractionDigits = state.settingsManager.preferences.bolusIncrement > 0.05 ? 1 : 2
  57. formatter.allowsFloats = true
  58. formatter.roundingIncrement = Double(state.settingsManager.preferences.bolusIncrement) as NSNumber
  59. return formatter
  60. }
  61. private var numberFormatter: NumberFormatter {
  62. let formatter = NumberFormatter()
  63. formatter.numberStyle = .decimal
  64. formatter.maximumFractionDigits = 2
  65. return formatter
  66. }
  67. private var fetchedTargetFormatter: NumberFormatter {
  68. let formatter = NumberFormatter()
  69. formatter.numberStyle = .decimal
  70. if state.units == .mmolL {
  71. formatter.maximumFractionDigits = 1
  72. } else { formatter.maximumFractionDigits = 0 }
  73. return formatter
  74. }
  75. private var targetFormatter: NumberFormatter {
  76. let formatter = NumberFormatter()
  77. formatter.numberStyle = .decimal
  78. formatter.maximumFractionDigits = 1
  79. return formatter
  80. }
  81. private var tirFormatter: NumberFormatter {
  82. let formatter = NumberFormatter()
  83. formatter.numberStyle = .decimal
  84. formatter.maximumFractionDigits = 0
  85. return formatter
  86. }
  87. private var dateFormatter: DateFormatter {
  88. let dateFormatter = DateFormatter()
  89. dateFormatter.timeStyle = .short
  90. return dateFormatter
  91. }
  92. private var color: LinearGradient {
  93. colorScheme == .dark ? LinearGradient(
  94. gradient: Gradient(colors: [
  95. Color.bgDarkBlue,
  96. Color.bgDarkerDarkBlue
  97. ]),
  98. startPoint: .top,
  99. endPoint: .bottom
  100. )
  101. :
  102. LinearGradient(
  103. gradient: Gradient(colors: [Color.gray.opacity(0.1)]),
  104. startPoint: .top,
  105. endPoint: .bottom
  106. )
  107. }
  108. private var historySFSymbol: String {
  109. if #available(iOS 17.0, *) {
  110. return "book.pages"
  111. } else {
  112. return "book"
  113. }
  114. }
  115. var glucoseView: some View {
  116. CurrentGlucoseView(
  117. timerDate: state.timerDate,
  118. units: state.units,
  119. alarm: state.alarm,
  120. lowGlucose: state.lowGlucose,
  121. highGlucose: state.highGlucose,
  122. cgmAvailable: state.cgmAvailable,
  123. currentGlucoseTarget: state.currentGlucoseTarget,
  124. glucoseColorScheme: state.glucoseColorScheme,
  125. glucose: state.latestTwoGlucoseValues
  126. ).scaleEffect(0.9)
  127. .onTapGesture {
  128. state.openCGM()
  129. }
  130. .onLongPressGesture {
  131. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  132. impactHeavy.impactOccurred()
  133. state.showModal(for: .snooze)
  134. }
  135. }
  136. var pumpView: some View {
  137. PumpView(
  138. reservoir: state.reservoir,
  139. name: state.pumpName,
  140. expiresAtDate: state.pumpExpiresAtDate,
  141. timerDate: state.timerDate,
  142. timeZone: state.timeZone,
  143. pumpStatusHighlightMessage: state.pumpStatusHighlightMessage,
  144. battery: state.batteryFromPersistence
  145. ).onTapGesture {
  146. if state.pumpDisplayState == nil {
  147. // shows user confirmation dialog with pump model choices, then proceeds to setup
  148. showPumpSelection.toggle()
  149. } else {
  150. // sends user to pump settings
  151. state.setupPump.toggle()
  152. }
  153. }
  154. }
  155. var tempBasalString: String? {
  156. guard let lastTempBasal = state.tempBasals.last?.tempBasal, let tempRate = lastTempBasal.rate else {
  157. return nil
  158. }
  159. let rateString = numberFormatter.string(from: tempRate as NSNumber) ?? "0"
  160. var manualBasalString = ""
  161. if let apsManager = state.apsManager, apsManager.isManualTempBasal {
  162. manualBasalString = NSLocalizedString(
  163. " - Manual Basal ⚠️",
  164. comment: "Manual Temp basal"
  165. )
  166. }
  167. return rateString + " " + NSLocalizedString(" U/hr", comment: "Unit per hour with space") + manualBasalString
  168. }
  169. var overrideString: String? {
  170. guard let latestOverride = latestOverride.first else {
  171. return nil
  172. }
  173. let percent = latestOverride.percentage
  174. let percentString = percent == 100 ? "" : "\(percent.formatted(.number)) %"
  175. let unit = state.units
  176. var target = (latestOverride.target ?? 100) as Decimal
  177. target = unit == .mmolL ? target.asMmolL : target
  178. var targetString = target == 0 ? "" : (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " + unit
  179. .rawValue
  180. if tempTargetString != nil {
  181. targetString = ""
  182. }
  183. let duration = latestOverride.duration ?? 0
  184. let addedMinutes = Int(truncating: duration)
  185. let date = latestOverride.date ?? Date()
  186. let newDuration = max(
  187. Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes),
  188. 0
  189. )
  190. let indefinite = latestOverride.indefinite
  191. var durationString = ""
  192. if !indefinite {
  193. if newDuration >= 1 {
  194. durationString = formatHrMin(Int(newDuration))
  195. } else if newDuration > 0 {
  196. durationString = "\(Int(newDuration * 60)) s"
  197. } else {
  198. /// Do not show the Override anymore
  199. Task {
  200. guard let objectID = self.latestOverride.first?.objectID else { return }
  201. await state.cancelOverride(withID: objectID)
  202. }
  203. }
  204. }
  205. let smbScheduleString = latestOverride
  206. .smbIsScheduledOff && ((latestOverride.start?.stringValue ?? "") != (latestOverride.end?.stringValue ?? ""))
  207. ? " \(formatTimeRange(start: latestOverride.start?.stringValue, end: latestOverride.end?.stringValue))"
  208. : ""
  209. let smbToggleString = latestOverride.smbIsOff || latestOverride
  210. .smbIsScheduledOff ? "SMBs Off\(smbScheduleString)" : ""
  211. let components = [durationString, percentString, targetString, smbToggleString].filter { !$0.isEmpty }
  212. return components.isEmpty ? nil : components.joined(separator: ", ")
  213. }
  214. var tempTargetString: String? {
  215. guard let latestTempTarget = latestTempTarget.first else {
  216. return nil
  217. }
  218. let duration = latestTempTarget.duration
  219. let addedMinutes = Int(truncating: duration ?? 0)
  220. let date = latestTempTarget.date ?? Date()
  221. let newDuration = max(
  222. Decimal(Date().distance(to: date.addingTimeInterval(addedMinutes.minutes.timeInterval)).minutes),
  223. 0
  224. )
  225. var durationString = ""
  226. var percentageString = ""
  227. var target = (latestTempTarget.target ?? 100) as Decimal
  228. var halfBasalTarget: Decimal = 160
  229. if latestTempTarget.halfBasalTarget != nil {
  230. halfBasalTarget = latestTempTarget.halfBasalTarget! as Decimal
  231. } else { halfBasalTarget = state.settingHalfBasalTarget }
  232. var showPercentage = false
  233. if target > 100, state.isExerciseModeActive || state.highTTraisesSens { showPercentage = true }
  234. if target < 100, state.lowTTlowersSens { showPercentage = true }
  235. if showPercentage {
  236. percentageString =
  237. " \(state.computeAdjustedPercentage(halfBasalTargetValue: halfBasalTarget, tempTargetValue: target))%" }
  238. target = state.units == .mmolL ? target.asMmolL : target
  239. let targetString = target == 0 ? "" : (fetchedTargetFormatter.string(from: target as NSNumber) ?? "") + " " +
  240. state.units.rawValue + percentageString
  241. if newDuration >= 1 {
  242. durationString =
  243. "\(newDuration.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) min"
  244. } else if newDuration > 0 {
  245. durationString =
  246. "\((newDuration * 60).formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))) s"
  247. } else {
  248. /// Do not show the Temp Target anymore
  249. Task {
  250. guard let objectID = self.latestTempTarget.first?.objectID else { return }
  251. await state.cancelTempTarget(withID: objectID)
  252. }
  253. }
  254. let components = [targetString, durationString].filter { !$0.isEmpty }
  255. return components.isEmpty ? nil : components.joined(separator: ", ")
  256. }
  257. var timeInterval: some View {
  258. HStack(alignment: .center) {
  259. ForEach(timeButtons) { button in
  260. Text(button.active ? NSLocalizedString(button.label, comment: "") : button.number).onTapGesture {
  261. state.hours = button.hours
  262. }
  263. .foregroundStyle(button.active ? (colorScheme == .dark ? Color.white : Color.black).opacity(0.9) : .secondary)
  264. .frame(maxHeight: 30).padding(.horizontal, 8)
  265. .background(
  266. button.active ?
  267. // RGB(30, 60, 95)
  268. (
  269. colorScheme == .dark ? Color(red: 0.1176470588, green: 0.2352941176, blue: 0.3725490196) :
  270. Color.white
  271. ) :
  272. Color
  273. .clear
  274. )
  275. .cornerRadius(20)
  276. }
  277. Button(action: {
  278. state.isLegendPresented.toggle()
  279. }) {
  280. Image(systemName: "info")
  281. .foregroundColor(colorScheme == .dark ? Color.white : Color.black).opacity(0.9)
  282. .frame(width: 20, height: 20)
  283. .background(
  284. colorScheme == .dark ? Color(red: 0.1176470588, green: 0.2352941176, blue: 0.3725490196) :
  285. Color.white
  286. )
  287. .clipShape(Circle())
  288. }
  289. .padding([.top, .bottom])
  290. }
  291. .shadow(
  292. color: Color.black.opacity(colorScheme == .dark ? 0.75 : 0.33),
  293. radius: colorScheme == .dark ? 5 : 3
  294. )
  295. .font(buttonFont)
  296. }
  297. @ViewBuilder func mainChart(geo: GeometryProxy) -> some View {
  298. ZStack {
  299. MainChartView(
  300. geo: geo,
  301. units: state.units,
  302. hours: state.filteredHours,
  303. tempTargets: state.tempTargets,
  304. highGlucose: state.highGlucose,
  305. lowGlucose: state.lowGlucose,
  306. currentGlucoseTarget: state.currentGlucoseTarget,
  307. glucoseColorScheme: state.glucoseColorScheme,
  308. screenHours: state.hours,
  309. displayXgridLines: state.displayXgridLines,
  310. displayYgridLines: state.displayYgridLines,
  311. thresholdLines: state.thresholdLines,
  312. state: state
  313. )
  314. }
  315. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: nil))
  316. }
  317. func highlightButtons() {
  318. for i in 0 ..< timeButtons.count {
  319. timeButtons[i].active = timeButtons[i].hours == state.hours
  320. }
  321. }
  322. @ViewBuilder func rightHeaderPanel(_: GeometryProxy) -> some View {
  323. VStack(alignment: .leading, spacing: 20) {
  324. /// Loop view at bottomLeading
  325. LoopView(
  326. closedLoop: state.closedLoop,
  327. timerDate: state.timerDate,
  328. isLooping: state.isLooping,
  329. lastLoopDate: state.lastLoopDate,
  330. manualTempBasal: state.manualTempBasal,
  331. determination: state.determinationsFromPersistence
  332. ).onTapGesture {
  333. state.isStatusPopupPresented = true
  334. setStatusTitle()
  335. }.onLongPressGesture {
  336. let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
  337. impactHeavy.impactOccurred()
  338. state.runLoop()
  339. }
  340. /// eventualBG string at bottomTrailing
  341. if let eventualBG = state.enactedAndNonEnactedDeterminations.first?.eventualBG {
  342. let bg = eventualBG as Decimal
  343. HStack {
  344. Image(systemName: "arrow.right.circle")
  345. .font(.system(size: 16, weight: .bold))
  346. Text(
  347. numberFormatter.string(
  348. from: (
  349. state.units == .mmolL ? bg
  350. .asMmolL : bg
  351. ) as NSNumber
  352. )!
  353. )
  354. .font(.system(size: 16))
  355. }
  356. } else {
  357. HStack {
  358. Image(systemName: "arrow.right.circle")
  359. .font(.system(size: 16, weight: .bold))
  360. Text("--")
  361. .font(.system(size: 16))
  362. }
  363. }
  364. }
  365. }
  366. @ViewBuilder func mealPanel(_: GeometryProxy) -> some View {
  367. HStack {
  368. HStack {
  369. Image(systemName: "syringe.fill")
  370. .font(.system(size: 16))
  371. .foregroundColor(Color.insulin)
  372. Text(
  373. (
  374. numberFormatter
  375. .string(from: (state.enactedAndNonEnactedDeterminations.first?.iob ?? 0) as NSNumber) ?? "0"
  376. ) +
  377. NSLocalizedString(" U", comment: "Insulin unit")
  378. )
  379. .font(.system(size: 16, weight: .bold, design: .rounded))
  380. }
  381. Spacer()
  382. HStack {
  383. Image(systemName: "fork.knife")
  384. .font(.system(size: 16))
  385. .foregroundColor(.loopYellow)
  386. Text(
  387. (
  388. numberFormatter.string(
  389. from: NSNumber(value: state.enactedAndNonEnactedDeterminations.first?.cob ?? 0)
  390. ) ?? "0"
  391. ) +
  392. NSLocalizedString(" g", comment: "gram of carbs")
  393. )
  394. .font(.system(size: 16, weight: .bold, design: .rounded))
  395. }
  396. Spacer()
  397. HStack {
  398. if state.pumpSuspended {
  399. Text("Pump suspended")
  400. .font(.system(size: 12, weight: .bold, design: .rounded)).foregroundColor(.loopGray)
  401. } else if let tempBasalString = tempBasalString {
  402. Image(systemName: "drop.circle")
  403. .font(.system(size: 16))
  404. .foregroundColor(.insulinTintColor)
  405. Text(tempBasalString)
  406. .font(.system(size: 16, weight: .bold, design: .rounded))
  407. } else {
  408. Image(systemName: "drop.circle")
  409. .font(.system(size: 16))
  410. .foregroundColor(.insulinTintColor)
  411. Text("No Data")
  412. .font(.system(size: 16, weight: .bold, design: .rounded))
  413. }
  414. }
  415. if state.totalInsulinDisplayType == .totalDailyDose {
  416. Spacer()
  417. Text(
  418. "TDD: " +
  419. (
  420. numberFormatter
  421. .string(from: (state.determinationsFromPersistence.first?.totalDailyDose ?? 0) as NSNumber) ??
  422. "0"
  423. ) +
  424. NSLocalizedString(" U", comment: "Insulin unit")
  425. )
  426. .font(.system(size: 16, weight: .bold, design: .rounded))
  427. } else {
  428. Spacer()
  429. HStack {
  430. Text(
  431. "TINS: \(state.roundedTotalBolus)" +
  432. NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)")
  433. )
  434. .font(.system(size: 16, weight: .bold, design: .rounded))
  435. .onChange(of: state.hours) {
  436. state.roundedTotalBolus = state.calculateTINS()
  437. }
  438. .onAppear {
  439. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  440. state.roundedTotalBolus = state.calculateTINS()
  441. }
  442. }
  443. }
  444. }
  445. }.padding(.horizontal, 10)
  446. }
  447. @ViewBuilder func adjustmentsOverrideView(_ overrideString: String) -> some View {
  448. Group {
  449. Image(systemName: "clock.arrow.2.circlepath")
  450. .font(.system(size: 20))
  451. .foregroundStyle(Color.primary, Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569))
  452. VStack(alignment: .leading) {
  453. Text(latestOverride.first?.name ?? "Custom Override")
  454. .font(.subheadline)
  455. .frame(alignment: .leading)
  456. Text(overrideString)
  457. .font(.caption)
  458. }
  459. }
  460. .onTapGesture {
  461. selectedTab = 2
  462. }
  463. }
  464. @ViewBuilder func adjustmentsTempTargetView(_ tempTargetString: String) -> some View {
  465. Group {
  466. Image(systemName: "target")
  467. .font(.system(size: 20))
  468. .foregroundStyle(Color.loopGreen)
  469. VStack(alignment: .leading) {
  470. Text(latestTempTarget.first?.name ?? "Temp Target")
  471. .font(.subheadline)
  472. Text(tempTargetString)
  473. .font(.caption)
  474. }
  475. }
  476. .onTapGesture {
  477. selectedTab = 2
  478. }
  479. }
  480. @ViewBuilder func adjustmentsCancelView(_ cancelAction: @escaping () -> Void) -> some View {
  481. Image(systemName: "xmark.app")
  482. .font(.system(size: 24))
  483. .onTapGesture {
  484. cancelAction()
  485. }
  486. }
  487. @ViewBuilder func adjustmentsCancelTempTargetView() -> some View {
  488. Image(systemName: "xmark.app")
  489. .font(.system(size: 24))
  490. .confirmationDialog(
  491. "Stop the Temp Target \"\(latestTempTarget.first?.name ?? "")\"?",
  492. isPresented: $isConfirmStopTempTargetShown,
  493. titleVisibility: .visible
  494. ) {
  495. Button("Stop", role: .destructive) {
  496. Task {
  497. guard let objectID = latestTempTarget.first?.objectID else { return }
  498. await state.cancelTempTarget(withID: objectID)
  499. }
  500. }
  501. Button("Cancel", role: .cancel) {}
  502. }
  503. .padding(.trailing, 8)
  504. .onTapGesture {
  505. if !latestTempTarget.isEmpty {
  506. isConfirmStopTempTargetShown = true
  507. }
  508. }
  509. }
  510. @ViewBuilder func adjustmentsCancelOverrideView() -> some View {
  511. Image(systemName: "xmark.app")
  512. .font(.system(size: 24))
  513. .confirmationDialog(
  514. "Stop the Override \"\(latestOverride.first?.name ?? "")\"?",
  515. isPresented: $isConfirmStopOverridePresented,
  516. titleVisibility: .visible
  517. ) {
  518. Button("Stop", role: .destructive) {
  519. Task {
  520. guard let objectID = latestOverride.first?.objectID else { return }
  521. await state.cancelOverride(withID: objectID)
  522. }
  523. }
  524. Button("Cancel", role: .cancel) {}
  525. }
  526. .padding(.trailing, 8)
  527. .onTapGesture {
  528. if !latestOverride.isEmpty {
  529. isConfirmStopOverridePresented = true
  530. }
  531. }
  532. }
  533. @ViewBuilder func noActiveAdjustmentsView() -> some View {
  534. Group {
  535. VStack {
  536. Text("No Active Adjustment")
  537. .font(.subheadline)
  538. .frame(maxWidth: .infinity, alignment: .leading)
  539. Text("Profile at 100 %")
  540. .font(.caption)
  541. .frame(maxWidth: .infinity, alignment: .leading)
  542. }.padding(.leading, 10)
  543. Spacer()
  544. /// to ensure the same position....
  545. Image(systemName: "xmark.app")
  546. .font(.system(size: 25))
  547. // clear color for the icon
  548. .foregroundStyle(Color.clear)
  549. }.onTapGesture {
  550. selectedTab = 2
  551. }
  552. }
  553. @ViewBuilder func adjustmentView(geo: GeometryProxy) -> some View {
  554. ZStack {
  555. /// rectangle as background
  556. RoundedRectangle(cornerRadius: 15)
  557. .fill(
  558. (overrideString != nil || tempTargetString != nil) ?
  559. (
  560. colorScheme == .dark ?
  561. Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) :
  562. Color.insulin.opacity(0.1)
  563. ) : Color.clear // Use clear and add the Material in the background
  564. )
  565. .background(.ultraThinMaterial)
  566. .clipShape(RoundedRectangle(cornerRadius: 15))
  567. .frame(height: geo.size.height * 0.08)
  568. .shadow(
  569. color: (overrideString != nil || tempTargetString != nil) ?
  570. (
  571. colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  572. Color.black.opacity(0.33)
  573. ) : Color.clear,
  574. radius: 3
  575. )
  576. HStack {
  577. if let overrideString = overrideString, let tempTargetString = tempTargetString {
  578. HStack {
  579. adjustmentsOverrideView(overrideString)
  580. Spacer()
  581. Divider()
  582. .frame(height: geo.size.height * 0.05)
  583. .padding(.horizontal, 2)
  584. adjustmentsTempTargetView(tempTargetString)
  585. Spacer()
  586. adjustmentsCancelView({
  587. if !latestTempTarget.isEmpty, !latestOverride.isEmpty {
  588. showCancelConfirmDialog = true
  589. } else if !latestOverride.isEmpty {
  590. showCancelAlert = true
  591. } else if !latestTempTarget.isEmpty {
  592. showCancelAlert = true
  593. }
  594. })
  595. }
  596. } else if let overrideString = overrideString {
  597. adjustmentsOverrideView(overrideString)
  598. Spacer()
  599. adjustmentsCancelOverrideView()
  600. } else if let tempTargetString = tempTargetString {
  601. HStack {
  602. adjustmentsTempTargetView(tempTargetString)
  603. Spacer()
  604. adjustmentsCancelTempTargetView()
  605. }
  606. } else {
  607. noActiveAdjustmentsView()
  608. }
  609. }.padding(.horizontal, 10)
  610. .confirmationDialog("Adjustment to Stop", isPresented: $showCancelConfirmDialog) {
  611. Button("Stop Override", role: .destructive) {
  612. Task {
  613. guard let objectID = latestOverride.first?.objectID else { return }
  614. await state.cancelOverride(withID: objectID)
  615. }
  616. }
  617. Button("Stop Temp Target", role: .destructive) {
  618. Task {
  619. guard let objectID = latestTempTarget.first?.objectID else { return }
  620. await state.cancelTempTarget(withID: objectID)
  621. }
  622. }
  623. Button("Stop All Adjustments", role: .destructive) {
  624. Task {
  625. guard let overrideObjectID = latestOverride.first?.objectID else { return }
  626. await state.cancelOverride(withID: overrideObjectID)
  627. guard let tempTargetObjectID = latestTempTarget.first?.objectID else { return }
  628. await state.cancelTempTarget(withID: tempTargetObjectID)
  629. }
  630. }
  631. } message: {
  632. Text("Select Adjustment")
  633. }
  634. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  635. }
  636. @ViewBuilder func bolusProgressBar(_ progress: Decimal) -> some View {
  637. GeometryReader { geo in
  638. RoundedRectangle(cornerRadius: 15)
  639. .frame(height: 6)
  640. .foregroundColor(.clear)
  641. .background(
  642. LinearGradient(colors: [
  643. Color(red: 0.7215686275, green: 0.3411764706, blue: 1),
  644. Color(red: 0.6235294118, green: 0.4235294118, blue: 0.9803921569),
  645. Color(red: 0.4862745098, green: 0.5450980392, blue: 0.9529411765),
  646. Color(red: 0.3411764706, green: 0.6666666667, blue: 0.9254901961),
  647. Color(red: 0.262745098, green: 0.7333333333, blue: 0.9137254902)
  648. ], startPoint: .leading, endPoint: .trailing)
  649. .mask(alignment: .leading) {
  650. RoundedRectangle(cornerRadius: 15)
  651. .frame(width: geo.size.width * CGFloat(progress))
  652. }
  653. )
  654. }
  655. }
  656. @ViewBuilder func bolusView(geo: GeometryProxy, _ progress: Decimal) -> some View {
  657. /// ensure that state.lastPumpBolus has a value, i.e. there is a last bolus done by the pump and not an external bolus
  658. /// - TRUE: show the pump bolus
  659. /// - FALSE: do not show a progress bar at all
  660. if let bolusTotal = state.lastPumpBolus?.bolus?.amount {
  661. let bolusFraction = progress * (bolusTotal as Decimal)
  662. let bolusString =
  663. (bolusProgressFormatter.string(from: bolusFraction as NSNumber) ?? "0")
  664. + " of " +
  665. (numberFormatter.string(from: bolusTotal as NSNumber) ?? "0")
  666. + NSLocalizedString(" U", comment: "Insulin unit")
  667. ZStack {
  668. /// rectangle as background
  669. RoundedRectangle(cornerRadius: 15)
  670. .fill(
  671. colorScheme == .dark ? Color(red: 0.03921568627, green: 0.133333333, blue: 0.2156862745) : Color
  672. .insulin
  673. .opacity(0.2)
  674. )
  675. .clipShape(RoundedRectangle(cornerRadius: 15))
  676. .frame(height: geo.size.height * 0.08)
  677. .shadow(
  678. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  679. Color.black.opacity(0.33),
  680. radius: 3
  681. )
  682. /// actual bolus view
  683. HStack {
  684. Image(systemName: "cross.vial.fill")
  685. .font(.system(size: 25))
  686. Spacer()
  687. VStack {
  688. Text("Bolusing")
  689. .font(.subheadline)
  690. .frame(maxWidth: .infinity, alignment: .leading)
  691. Text(bolusString)
  692. .font(.caption)
  693. .frame(maxWidth: .infinity, alignment: .leading)
  694. }.padding(.leading, 5)
  695. Spacer()
  696. Button {
  697. state.showProgressView()
  698. state.cancelBolus()
  699. } label: {
  700. Image(systemName: "xmark.app")
  701. .font(.system(size: 25))
  702. }
  703. }.padding(.horizontal, 10)
  704. .padding(.trailing, 8)
  705. }.padding(.horizontal, 10).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 10))
  706. .overlay(alignment: .bottom) {
  707. bolusProgressBar(progress).padding(.horizontal, 18).offset(y: 48)
  708. }.clipShape(RoundedRectangle(cornerRadius: 15))
  709. }
  710. }
  711. @ViewBuilder func alertSafetyNotificationsView(geo: GeometryProxy) -> some View {
  712. ZStack {
  713. /// rectangle as background
  714. RoundedRectangle(cornerRadius: 15)
  715. .fill(
  716. Color(
  717. red: 0.9,
  718. green: 0.133333333,
  719. blue: 0.2156862745
  720. )
  721. )
  722. .clipShape(RoundedRectangle(cornerRadius: 15))
  723. .frame(height: geo.size.height * 0.08)
  724. .coordinateSpace(name: "alertSafetyNotificationsView")
  725. .shadow(
  726. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  727. Color.black.opacity(0.33),
  728. radius: 3
  729. )
  730. HStack {
  731. Spacer()
  732. VStack {
  733. Text("⚠️ Safety Notifications are OFF")
  734. .font(.subheadline)
  735. .font(.system(size: 15, weight: .bold, design: .rounded))
  736. .foregroundStyle(.white.gradient)
  737. .frame(maxWidth: .infinity, alignment: .leading)
  738. Text("Fix now by turning Notifications ON.")
  739. .font(.caption)
  740. .font(.system(size: 12, weight: .bold, design: .rounded))
  741. .foregroundStyle(.white.gradient)
  742. .frame(maxWidth: .infinity, alignment: .leading)
  743. }.padding(.leading, 5)
  744. Spacer()
  745. Image(systemName: "chevron.right").foregroundColor(.white)
  746. .font(.system(size: 15, design: .rounded))
  747. }.padding(.horizontal, 10)
  748. .padding(.trailing, 8)
  749. .onTapGesture {
  750. UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
  751. }
  752. }.padding(.horizontal, 10)
  753. .padding(.top, 0)
  754. }
  755. @ViewBuilder func mainViewWithScrollView() -> some View {
  756. GeometryReader { geo in
  757. ScrollView(.vertical, showsIndicators: false) {
  758. mainViewViews(geo)
  759. }
  760. }
  761. }
  762. @ViewBuilder func mainViewViews(_ geo: GeometryProxy) -> some View {
  763. VStack(spacing: 0) {
  764. if notificationsDisabled {
  765. alertSafetyNotificationsView(geo: geo)
  766. .padding(.top, UIDevice.adjustPadding(min: nil, max: 40))
  767. }
  768. ZStack {
  769. /// glucose bobble
  770. glucoseView
  771. /// right panel with loop status and evBG
  772. HStack {
  773. Spacer()
  774. rightHeaderPanel(geo)
  775. }.padding(.trailing, 20)
  776. /// left panel with pump related info
  777. HStack {
  778. pumpView
  779. Spacer()
  780. }.padding(.leading, 20)
  781. }.padding(.top, 10)
  782. mealPanel(geo).padding(.top, UIDevice.adjustPadding(min: nil, max: 30))
  783. .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 20))
  784. mainChart(geo: geo)
  785. timeInterval.padding(.top, UIDevice.adjustPadding(min: 0, max: 12))
  786. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: 12))
  787. if let progress = state.bolusProgress {
  788. bolusView(geo: geo, progress)
  789. .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  790. } else {
  791. adjustmentView(geo: geo).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  792. }
  793. }
  794. .background(color)
  795. .onReceive(
  796. resolver.resolve(AlertPermissionsChecker.self)!.$notificationsDisabled,
  797. perform: {
  798. if notificationsDisabled != $0 {
  799. notificationsDisabled = $0
  800. if notificationsDisabled {
  801. debug(.default, "notificationsDisabled")
  802. }
  803. }
  804. }
  805. )
  806. }
  807. @ViewBuilder func mainView() -> some View {
  808. GeometryReader { geo in
  809. if notificationsDisabled {
  810. ScrollView(.vertical, showsIndicators: false) {
  811. mainViewViews(geo)
  812. }
  813. } else {
  814. GeometryReader { geo in
  815. mainViewViews(geo)
  816. }
  817. }
  818. }
  819. .onChange(of: state.hours) {
  820. highlightButtons()
  821. }
  822. .onAppear {
  823. configureView {
  824. highlightButtons()
  825. }
  826. }
  827. .navigationTitle("Home")
  828. .navigationBarHidden(true)
  829. .ignoresSafeArea(.keyboard)
  830. .popup(isPresented: state.isStatusPopupPresented, alignment: .top, direction: .top) {
  831. popup
  832. .padding()
  833. .background(
  834. RoundedRectangle(cornerRadius: 8, style: .continuous)
  835. .fill(colorScheme == .dark ? Color(
  836. "Chart"
  837. ) : Color(UIColor.darkGray))
  838. )
  839. .onTapGesture {
  840. state.isStatusPopupPresented = false
  841. }
  842. .gesture(
  843. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  844. .onEnded { value in
  845. if value.translation.height < 0 {
  846. state.isStatusPopupPresented = false
  847. }
  848. }
  849. )
  850. }
  851. .confirmationDialog("Pump Model", isPresented: $showPumpSelection) {
  852. Button("Medtronic") { state.addPump(.minimed) }
  853. Button("Omnipod Eros") { state.addPump(.omnipod) }
  854. Button("Omnipod Dash") { state.addPump(.omnipodBLE) }
  855. Button("Pump Simulator") { state.addPump(.simulator) }
  856. } message: { Text("Select Pump Model") }
  857. .sheet(isPresented: $state.setupPump) {
  858. if let pumpManager = state.provider.apsManager.pumpManager {
  859. PumpConfig.PumpSettingsView(
  860. pumpManager: pumpManager,
  861. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  862. completionDelegate: state,
  863. setupDelegate: state
  864. )
  865. } else {
  866. PumpConfig.PumpSetupView(
  867. pumpType: state.setupPumpType,
  868. pumpInitialSettings: PumpConfig.PumpInitialSettings.default,
  869. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  870. completionDelegate: state,
  871. setupDelegate: state
  872. )
  873. }
  874. }
  875. .sheet(isPresented: $state.isLegendPresented) {
  876. NavigationStack {
  877. Text(
  878. "The oref algorithm determines insulin dosing based on a number of scenarios that it estimates with different types of forecasts."
  879. )
  880. .font(.subheadline)
  881. .foregroundColor(.secondary)
  882. if state.forecastDisplayType == .lines {
  883. List {
  884. DefinitionRow(
  885. term: "IOB (Insulin on Board)",
  886. definition: "Forecasts BG based on the amount of insulin still active in the body.",
  887. color: .insulin
  888. )
  889. DefinitionRow(
  890. term: "ZT (Zero-Temp)",
  891. definition: "Forecasts the worst-case blood glucose (BG) scenario if no carbs are absorbed and insulin delivery is stopped until BG starts rising.",
  892. color: .zt
  893. )
  894. DefinitionRow(
  895. term: "COB (Carbs on Board)",
  896. definition: "Forecasts BG changes by considering the amount of carbohydrates still being absorbed in the body.",
  897. color: .loopYellow
  898. )
  899. DefinitionRow(
  900. term: "UAM (Unannounced Meal)",
  901. definition: "Forecasts BG levels and insulin dosing needs for unexpected meals or other causes of BG rises without prior notice.",
  902. color: .uam
  903. )
  904. }
  905. .padding(.trailing, 10)
  906. .navigationBarTitle("Legend", displayMode: .inline)
  907. } else {
  908. List {
  909. DefinitionRow(
  910. term: "Cone of Uncertainty",
  911. definition: "For simplicity reasons, oref's various forecast curves are displayed as a \"Cone of Uncertainty\" that depicts a possible, forecasted range of future glucose fluctuation based on the current data and the algothim's result.\n\nTo modify the forecast display type, go to Trio Settings > Features > User Interface > Forecast Display Type.",
  912. color: Color.blue.opacity(0.5)
  913. )
  914. }
  915. .padding(.trailing, 10)
  916. .navigationBarTitle("Legend", displayMode: .inline)
  917. }
  918. Button { state.isLegendPresented.toggle() }
  919. label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  920. .buttonStyle(.bordered)
  921. .padding(.top)
  922. }
  923. .padding()
  924. .presentationDetents(
  925. [.fraction(0.9), .large],
  926. selection: $state.legendSheetDetent
  927. )
  928. }
  929. }
  930. // @ViewBuilder func mainView() -> some View {
  931. // GeometryReader { geo in
  932. // if notificationsDisabled {
  933. // ScrollView(.vertical, showsIndicators: false) {
  934. // mainViewViews(geo)
  935. // }
  936. // } else {
  937. // GeometryReader { geo in
  938. // mainViewViews(geo)
  939. // >>>>>>> 04a9930af6fb5a25c8ee00e1e9fd788663eb4f7c
  940. // }
  941. // }
  942. // }
  943. // .onChange(of: state.hours) {
  944. // highlightButtons()
  945. // }
  946. // .onAppear {
  947. // configureView {
  948. // highlightButtons()
  949. // }
  950. // }
  951. // .navigationTitle("Home")
  952. // .navigationBarHidden(true)
  953. // .ignoresSafeArea(.keyboard)
  954. // .popup(isPresented: state.isStatusPopupPresented, alignment: .top, direction: .top) {
  955. // popup
  956. // .padding()
  957. // .background(
  958. // RoundedRectangle(cornerRadius: 8, style: .continuous)
  959. // .fill(colorScheme == .dark ? Color(
  960. // "Chart"
  961. // ) : Color(UIColor.darkGray))
  962. // )
  963. // .onTapGesture {
  964. // state.isStatusPopupPresented = false
  965. // }
  966. // .gesture(
  967. // DragGesture(minimumDistance: 10, coordinateSpace: .local)
  968. // .onEnded { value in
  969. // if value.translation.height < 0 {
  970. // state.isStatusPopupPresented = false
  971. // }
  972. // }
  973. // )
  974. // }
  975. // .confirmationDialog("Pump Model", isPresented: $showPumpSelection) {
  976. // Button("Medtronic") { state.addPump(.minimed) }
  977. // Button("Omnipod Eros") { state.addPump(.omnipod) }
  978. // Button("Omnipod Dash") { state.addPump(.omnipodBLE) }
  979. // Button("Pump Simulator") { state.addPump(.simulator) }
  980. // } message: { Text("Select Pump Model") }
  981. // .sheet(isPresented: $state.setupPump) {
  982. // if let pumpManager = state.provider.apsManager.pumpManager {
  983. // PumpConfig.PumpSettingsView(
  984. // pumpManager: pumpManager,
  985. // bluetoothManager: state.provider.apsManager.bluetoothManager!,
  986. // completionDelegate: state,
  987. // setupDelegate: state
  988. // )
  989. // } else {
  990. // PumpConfig.PumpSetupView(
  991. // pumpType: state.setupPumpType,
  992. // pumpInitialSettings: PumpConfig.PumpInitialSettings.default,
  993. // bluetoothManager: state.provider.apsManager.bluetoothManager!,
  994. // completionDelegate: state,
  995. // setupDelegate: state
  996. // )
  997. // }
  998. // }
  999. // .sheet(isPresented: $state.isLegendPresented) {
  1000. // NavigationStack {
  1001. // Text(
  1002. // "The oref algorithm determines insulin dosing based on a number of scenarios that it estimates with different types of forecasts."
  1003. // )
  1004. // .font(.subheadline)
  1005. // .foregroundColor(.secondary)
  1006. //
  1007. // if state.forecastDisplayType == .lines {
  1008. // List {
  1009. // DefinitionRow(
  1010. // term: "IOB (Insulin on Board)",
  1011. // definition: "Forecasts BG based on the amount of insulin still active in the body.",
  1012. // color: .insulin
  1013. // )
  1014. // DefinitionRow(
  1015. // term: "ZT (Zero-Temp)",
  1016. // definition: "Forecasts the worst-case blood glucose (BG) scenario if no carbs are absorbed and insulin delivery is stopped until BG starts rising.",
  1017. // color: .zt
  1018. // )
  1019. // DefinitionRow(
  1020. // term: "COB (Carbs on Board)",
  1021. // definition: "Forecasts BG changes by considering the amount of carbohydrates still being absorbed in the body.",
  1022. // color: .loopYellow
  1023. // )
  1024. // DefinitionRow(
  1025. // term: "UAM (Unannounced Meal)",
  1026. // definition: "Forecasts BG levels and insulin dosing needs for unexpected meals or other causes of BG rises without prior notice.",
  1027. // color: .uam
  1028. // )
  1029. // }
  1030. // .padding(.trailing, 10)
  1031. // .navigationBarTitle("Legend", displayMode: .inline)
  1032. // } else {
  1033. // List {
  1034. // DefinitionRow(
  1035. // term: "Cone of Uncertainty",
  1036. // definition: "For simplicity reasons, oref's various forecast curves are displayed as a \"Cone of Uncertainty\" that depicts a possible, forecasted range of future glucose fluctuation based on the current data and the algothim's result.\n\nTo modify the forecast display type, go to Trio Settings > Features > User Interface > Forecast Display Type.",
  1037. // color: Color.blue.opacity(0.5)
  1038. // )
  1039. // }
  1040. // .padding(.trailing, 10)
  1041. // .navigationBarTitle("Legend", displayMode: .inline)
  1042. // }
  1043. //
  1044. // Button { state.isLegendPresented.toggle() }
  1045. // label: { Text("Got it!").frame(maxWidth: .infinity, alignment: .center) }
  1046. // .buttonStyle(.bordered)
  1047. // .padding(.top)
  1048. // }
  1049. // .padding()
  1050. // .presentationDetents(
  1051. // [.fraction(0.9), .large],
  1052. // selection: $state.legendSheetDetent
  1053. // )
  1054. // }
  1055. // }
  1056. @State var settingsPath = NavigationPath()
  1057. @ViewBuilder func tabBar() -> some View {
  1058. ZStack(alignment: .bottom) {
  1059. TabView(selection: $selectedTab) {
  1060. let carbsRequiredBadge: String? = {
  1061. guard let carbsRequired = state.enactedAndNonEnactedDeterminations.first?.carbsRequired,
  1062. state.showCarbsRequiredBadge
  1063. else {
  1064. return nil
  1065. }
  1066. let carbsRequiredDecimal = Decimal(carbsRequired)
  1067. if carbsRequiredDecimal > state.settingsManager.settings.carbsRequiredThreshold {
  1068. let numberAsNSNumber = NSDecimalNumber(decimal: carbsRequiredDecimal)
  1069. return (numberFormatter.string(from: numberAsNSNumber) ?? "") + " g"
  1070. }
  1071. return nil
  1072. }()
  1073. NavigationStack { mainView() }
  1074. .tabItem { Label("Main", systemImage: "chart.xyaxis.line") }
  1075. .badge(carbsRequiredBadge).tag(0)
  1076. NavigationStack { DataTable.RootView(resolver: resolver) }
  1077. .tabItem { Label("History", systemImage: historySFSymbol) }.tag(1)
  1078. Spacer()
  1079. NavigationStack { Adjustments.RootView(resolver: resolver) }
  1080. .tabItem {
  1081. Label(
  1082. "Adjustments",
  1083. systemImage: "slider.horizontal.2.gobackward"
  1084. ) }.tag(2)
  1085. NavigationStack(path: self.$settingsPath) {
  1086. Settings.RootView(resolver: resolver) }
  1087. .tabItem { Label(
  1088. "Settings",
  1089. systemImage: "gear"
  1090. ) }.tag(3)
  1091. }
  1092. .tint(Color.tabBar)
  1093. Button(
  1094. action: {
  1095. state.showModal(for: .bolus) },
  1096. label: {
  1097. Image(systemName: "plus.circle.fill")
  1098. .font(.system(size: 40))
  1099. .foregroundStyle(Color.tabBar)
  1100. .padding(.bottom, 1)
  1101. .padding(.horizontal, 20)
  1102. }
  1103. )
  1104. }.ignoresSafeArea(.keyboard, edges: .bottom).blur(radius: state.waitForSuggestion ? 8 : 0)
  1105. .onChange(of: selectedTab) {
  1106. print("current path is empty: \(settingsPath.isEmpty)")
  1107. settingsPath = NavigationPath()
  1108. }
  1109. }
  1110. var body: some View {
  1111. ZStack(alignment: .center) {
  1112. tabBar()
  1113. if state.waitForSuggestion {
  1114. CustomProgressView(text: "Updating IOB...")
  1115. }
  1116. }
  1117. }
  1118. private func parseReasonConclusion(_ reasonConclusion: String, isMmolL: Bool) -> String {
  1119. var updatedConclusion = reasonConclusion
  1120. // Handle "minGuardBG x<y" pattern
  1121. if let range = updatedConclusion.range(of: "minGuardBG\\s*-?\\d+<\\d+", options: .regularExpression) {
  1122. let matchedString = updatedConclusion[range]
  1123. let parts = matchedString.components(separatedBy: "<")
  1124. if let firstValue = Double(parts[0].components(separatedBy: CharacterSet.decimalDigits.inverted).joined()),
  1125. let secondValue = Double(parts[1])
  1126. {
  1127. let formattedFirstValue = isMmolL ? Double(firstValue.asMmolL) : firstValue
  1128. let formattedSecondValue = isMmolL ? Double(secondValue.asMmolL) : secondValue
  1129. let formattedString = "minGuardBG \(formattedFirstValue)<\(formattedSecondValue)"
  1130. updatedConclusion = updatedConclusion.replacingOccurrences(of: matchedString, with: formattedString)
  1131. }
  1132. }
  1133. // Handle "Eventual BG x >= target" pattern
  1134. if let range = updatedConclusion.range(of: "Eventual BG\\s*\\d+\\s*>?=\\s*\\d+", options: .regularExpression) {
  1135. let matchedString = updatedConclusion[range]
  1136. let parts = matchedString.components(separatedBy: " >= ")
  1137. if let firstValue = Double(parts[0].components(separatedBy: CharacterSet.decimalDigits.inverted).joined()),
  1138. let secondValue = Double(parts[1])
  1139. {
  1140. let formattedFirstValue = isMmolL ? Double(firstValue.asMmolL) : firstValue
  1141. let formattedSecondValue = isMmolL ? Double(secondValue.asMmolL) : secondValue
  1142. let formattedString = "Eventual BG \(formattedFirstValue) >= \(formattedSecondValue)"
  1143. updatedConclusion = updatedConclusion.replacingOccurrences(of: matchedString, with: formattedString)
  1144. }
  1145. }
  1146. return updatedConclusion.capitalizingFirstLetter()
  1147. }
  1148. private var popup: some View {
  1149. VStack(alignment: .leading, spacing: 4) {
  1150. Text(statusTitle).font(.headline).foregroundColor(.white)
  1151. .padding(.bottom, 4)
  1152. if let determination = state.determinationsFromPersistence.first {
  1153. if determination.glucose == 400 {
  1154. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  1155. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  1156. } else {
  1157. let tags = !state.isSmoothingEnabled ? determination.reasonParts : determination
  1158. .reasonParts + ["Smoothing: On"]
  1159. TagCloudView(
  1160. tags: tags,
  1161. shouldParseToMmolL: state.units == .mmolL
  1162. )
  1163. .animation(.none, value: false)
  1164. Text(
  1165. self
  1166. .parseReasonConclusion(
  1167. determination.reasonConclusion,
  1168. isMmolL: state.units == .mmolL
  1169. )
  1170. ).font(.caption).foregroundColor(.white)
  1171. }
  1172. } else {
  1173. Text("No determination found").font(.body).foregroundColor(.white)
  1174. }
  1175. if let errorMessage = state.errorMessage, let date = state.errorDate {
  1176. Text(NSLocalizedString("Error at", comment: "") + " " + dateFormatter.string(from: date))
  1177. .foregroundColor(.white)
  1178. .font(.headline)
  1179. .padding(.bottom, 4)
  1180. .padding(.top, 8)
  1181. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  1182. }
  1183. }
  1184. }
  1185. private func setStatusTitle() {
  1186. if let determination = state.determinationsFromPersistence.first {
  1187. let dateFormatter = DateFormatter()
  1188. dateFormatter.timeStyle = .short
  1189. statusTitle = NSLocalizedString("Oref Determination enacted at", comment: "Headline in enacted pop up") +
  1190. " " +
  1191. dateFormatter
  1192. .string(from: determination.deliverAt ?? Date())
  1193. } else {
  1194. statusTitle = "No Oref determination"
  1195. return
  1196. }
  1197. }
  1198. }
  1199. }
  1200. extension UIDevice {
  1201. public enum DeviceSize: CGFloat {
  1202. case smallDevice = 667 // Height for 4" iPhone SE
  1203. case largeDevice = 852 // Height for 6.1" iPhone 15 Pro
  1204. }
  1205. @usableFromInline static func adjustPadding(
  1206. min: CGFloat? = nil,
  1207. max: CGFloat? = nil
  1208. ) -> CGFloat? {
  1209. if UIScreen.screenHeight > UIDevice.DeviceSize.smallDevice.rawValue {
  1210. if UIScreen.screenHeight >= UIDevice.DeviceSize.largeDevice.rawValue {
  1211. return max
  1212. } else {
  1213. return min != nil ?
  1214. (max != nil ? max! * (UIScreen.screenHeight / UIDevice.DeviceSize.largeDevice.rawValue) : nil) : nil
  1215. }
  1216. } else {
  1217. return min
  1218. }
  1219. }
  1220. }
  1221. extension UIScreen {
  1222. static var screenHeight: CGFloat {
  1223. UIScreen.main.bounds.height
  1224. }
  1225. static var screenWidth: CGFloat {
  1226. UIScreen.main.bounds.width
  1227. }
  1228. }
  1229. // Helper function to convert a start and end hour to either 24-hour or AM/PM format
  1230. func formatTimeRange(start: String?, end: String?) -> String {
  1231. guard let start = start, let end = end else {
  1232. return ""
  1233. }
  1234. // Check if the format is 24-hour or AM/PM
  1235. if is24HourFormat() {
  1236. // Return the original 24-hour format
  1237. return "\(start)-\(end)"
  1238. } else {
  1239. // Convert to AM/PM format using DateFormatter
  1240. let formatter = DateFormatter()
  1241. formatter.dateFormat = "HH"
  1242. if let startHour = Int(start), let endHour = Int(end) {
  1243. let startDate = Calendar.current.date(bySettingHour: startHour, minute: 0, second: 0, of: Date()) ?? Date()
  1244. let endDate = Calendar.current.date(bySettingHour: endHour, minute: 0, second: 0, of: Date()) ?? Date()
  1245. // Customize the format to "2p" or "2a"
  1246. formatter.dateFormat = "ha"
  1247. let startFormatted = formatter.string(from: startDate).lowercased().replacingOccurrences(of: "m", with: "")
  1248. let endFormatted = formatter.string(from: endDate).lowercased().replacingOccurrences(of: "m", with: "")
  1249. return "\(startFormatted)-\(endFormatted)"
  1250. } else {
  1251. return ""
  1252. }
  1253. }
  1254. }