HomeRootView.swift 56 KB

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