HomeRootView.swift 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  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. // Use a geo-based offset here to position progress bar independent of device size
  671. let offset = geo.size.height * 0.0725
  672. bolusProgressBar(progress).padding(.horizontal, 18)
  673. .offset(y: offset)
  674. }.clipShape(RoundedRectangle(cornerRadius: 15))
  675. }
  676. }
  677. @ViewBuilder func alertSafetyNotificationsView(geo: GeometryProxy) -> some View {
  678. ZStack {
  679. /// rectangle as background
  680. RoundedRectangle(cornerRadius: 15)
  681. .fill(
  682. Color(
  683. red: 0.9,
  684. green: 0.133333333,
  685. blue: 0.2156862745
  686. )
  687. )
  688. .clipShape(RoundedRectangle(cornerRadius: 15))
  689. .frame(height: geo.size.height * safeAreaSize)
  690. .coordinateSpace(name: "alertSafetyNotificationsView")
  691. .shadow(
  692. color: colorScheme == .dark ? Color(red: 0.02745098039, green: 0.1098039216, blue: 0.1411764706) :
  693. Color.black.opacity(0.33),
  694. radius: 3
  695. )
  696. HStack {
  697. Spacer()
  698. VStack {
  699. Text("⚠️ Safety Notifications are OFF")
  700. .font(.headline)
  701. .fontWeight(.bold)
  702. .fontDesign(.rounded)
  703. .foregroundStyle(.white.gradient)
  704. .frame(maxWidth: .infinity, alignment: .leading)
  705. Text("Fix now by turning Notifications ON.")
  706. .font(.footnote)
  707. .fontDesign(.rounded)
  708. .foregroundStyle(.white.gradient)
  709. .frame(maxWidth: .infinity, alignment: .leading)
  710. }.padding(.leading, 5)
  711. Spacer()
  712. Image(systemName: "chevron.right").foregroundColor(.white)
  713. .font(.headline)
  714. }.padding(.horizontal, 10)
  715. .padding(.trailing, 8)
  716. .onTapGesture {
  717. UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
  718. }
  719. }.padding(.horizontal, 10)
  720. .padding(.top, 0)
  721. }
  722. @ViewBuilder func mainViewElements(_ geo: GeometryProxy) -> some View {
  723. VStack(spacing: 0) {
  724. ZStack {
  725. /// glucose bobble
  726. glucoseView
  727. /// right panel with loop status and evBG
  728. HStack {
  729. Spacer()
  730. rightHeaderPanel(geo)
  731. }.padding(.trailing, 20)
  732. /// left panel with pump related info
  733. HStack {
  734. pumpView
  735. Spacer()
  736. }.padding(.leading, 20)
  737. }.padding(.top, 10)
  738. .safeAreaInset(edge: .top, spacing: 0) {
  739. if notificationsDisabled {
  740. alertSafetyNotificationsView(geo: geo)
  741. }
  742. }
  743. mealPanel(geo).padding(.top, UIDevice.adjustPadding(min: nil, max: 30))
  744. .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 20))
  745. mainChart(geo: geo)
  746. timeInterval.padding(.top, UIDevice.adjustPadding(min: 0, max: 12))
  747. .padding(.bottom, UIDevice.adjustPadding(min: 0, max: 12))
  748. if let progress = state.bolusProgress {
  749. bolusView(geo: geo, progress)
  750. .padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  751. } else {
  752. adjustmentView(geo: geo).padding(.bottom, UIDevice.adjustPadding(min: nil, max: 40))
  753. }
  754. }
  755. .background(appState.trioBackgroundColor(for: colorScheme))
  756. .onReceive(
  757. resolver.resolve(AlertPermissionsChecker.self)!.$notificationsDisabled,
  758. perform: {
  759. if notificationsDisabled != $0 {
  760. notificationsDisabled = $0
  761. if notificationsDisabled {
  762. debug(.default, "notificationsDisabled")
  763. }
  764. }
  765. }
  766. )
  767. }
  768. @ViewBuilder func mainView() -> some View {
  769. GeometryReader { geo in
  770. mainViewElements(geo)
  771. }
  772. .onChange(of: state.hours) {
  773. highlightButtons()
  774. }
  775. .onAppear {
  776. configureView {
  777. highlightButtons()
  778. }
  779. }
  780. .navigationTitle("Home")
  781. .navigationBarHidden(true)
  782. .ignoresSafeArea(.keyboard)
  783. .popup(isPresented: state.isStatusPopupPresented, alignment: .top, direction: .top) {
  784. popup
  785. .padding()
  786. .background(
  787. RoundedRectangle(cornerRadius: 8, style: .continuous)
  788. .fill(colorScheme == .dark ? Color(
  789. "Chart"
  790. ) : Color(UIColor.darkGray))
  791. )
  792. .onTapGesture {
  793. state.isStatusPopupPresented = false
  794. }
  795. .gesture(
  796. DragGesture(minimumDistance: 10, coordinateSpace: .local)
  797. .onEnded { value in
  798. if value.translation.height < 0 {
  799. state.isStatusPopupPresented = false
  800. }
  801. }
  802. )
  803. }
  804. .confirmationDialog("Pump Model", isPresented: $showPumpSelection) {
  805. Button("Medtronic") { state.addPump(.minimed) }
  806. Button("Omnipod Eros") { state.addPump(.omnipod) }
  807. Button("Omnipod Dash") { state.addPump(.omnipodBLE) }
  808. Button("Pump Simulator") { state.addPump(.simulator) }
  809. } message: { Text("Select Pump Model") }
  810. .sheet(isPresented: $state.setupPump) {
  811. if let pumpManager = state.provider.apsManager.pumpManager {
  812. PumpConfig.PumpSettingsView(
  813. pumpManager: pumpManager,
  814. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  815. completionDelegate: state,
  816. setupDelegate: state
  817. )
  818. } else {
  819. PumpConfig.PumpSetupView(
  820. pumpType: state.setupPumpType,
  821. pumpInitialSettings: PumpConfig.PumpInitialSettings.default,
  822. bluetoothManager: state.provider.apsManager.bluetoothManager!,
  823. completionDelegate: state,
  824. setupDelegate: state
  825. )
  826. }
  827. }
  828. .sheet(isPresented: $state.isLegendPresented) {
  829. legendSheetView()
  830. }
  831. }
  832. @ViewBuilder func legendSheetView() -> some View {
  833. NavigationStack {
  834. VStack(alignment: .leading, spacing: 16) {
  835. Text(
  836. "The oref algorithm determines insulin dosing based on a number of scenarios that it estimates with different types of forecasts."
  837. )
  838. .font(.subheadline)
  839. .foregroundColor(.secondary)
  840. if state.forecastDisplayType == .lines {
  841. legendLinesView()
  842. } else {
  843. legendConeOfUncertaintyView()
  844. }
  845. Button {
  846. state.isLegendPresented.toggle()
  847. } label: {
  848. Text("Got it!")
  849. .frame(maxWidth: .infinity, alignment: .center)
  850. }
  851. .buttonStyle(.bordered)
  852. .padding(.top)
  853. }
  854. .padding()
  855. .presentationDetents(
  856. [.fraction(0.9), .large],
  857. selection: $state.legendSheetDetent
  858. )
  859. }
  860. }
  861. @ViewBuilder func legendLinesView() -> some View {
  862. List {
  863. DefinitionRow(
  864. term: "IOB (Insulin on Board)",
  865. definition: "Forecasts BG based on the amount of insulin still active in the body.",
  866. color: .insulin
  867. )
  868. DefinitionRow(
  869. term: "ZT (Zero-Temp)",
  870. definition: "Forecasts the worst-case blood glucose (BG) scenario if no carbs are absorbed and insulin delivery is stopped until BG starts rising.",
  871. color: .zt
  872. )
  873. DefinitionRow(
  874. term: "COB (Carbs on Board)",
  875. definition: "Forecasts BG changes by considering the amount of carbohydrates still being absorbed in the body.",
  876. color: .loopYellow
  877. )
  878. DefinitionRow(
  879. term: "UAM (Unannounced Meal)",
  880. definition: "Forecasts BG levels and insulin dosing needs for unexpected meals or other causes of BG rises without prior notice.",
  881. color: .uam
  882. )
  883. }
  884. .padding(.trailing, 10)
  885. .navigationBarTitle("Legend", displayMode: .inline)
  886. }
  887. @ViewBuilder func legendConeOfUncertaintyView() -> some View {
  888. List {
  889. DefinitionRow(
  890. term: "Cone of Uncertainty",
  891. definition: """
  892. 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.
  893. To modify the forecast display type, go to Trio Settings > Features > User Interface > Forecast Display Type.
  894. """,
  895. color: Color.blue.opacity(0.5)
  896. )
  897. }
  898. .padding(.trailing, 10)
  899. .navigationBarTitle("Legend", displayMode: .inline)
  900. }
  901. @ViewBuilder func tabBar() -> some View {
  902. ZStack(alignment: .bottom) {
  903. TabView(selection: $selectedTab) {
  904. let carbsRequiredBadge: String? = {
  905. guard let carbsRequired = state.enactedAndNonEnactedDeterminations.first?.carbsRequired,
  906. state.showCarbsRequiredBadge
  907. else {
  908. return nil
  909. }
  910. let carbsRequiredDecimal = Decimal(carbsRequired)
  911. if carbsRequiredDecimal > state.settingsManager.settings.carbsRequiredThreshold {
  912. let numberAsNSNumber = NSDecimalNumber(decimal: carbsRequiredDecimal)
  913. return (Formatter.decimalFormatterWithTwoFractionDigits.string(from: numberAsNSNumber) ?? "") + " g"
  914. }
  915. return nil
  916. }()
  917. NavigationStack { mainView() }
  918. .tabItem { Label("Main", systemImage: "chart.xyaxis.line") }
  919. .badge(carbsRequiredBadge).tag(0)
  920. NavigationStack { DataTable.RootView(resolver: resolver) }
  921. .tabItem { Label("History", systemImage: historySFSymbol) }.tag(1)
  922. Spacer()
  923. NavigationStack { Adjustments.RootView(resolver: resolver) }
  924. .tabItem {
  925. Label(
  926. "Adjustments",
  927. systemImage: "slider.horizontal.2.gobackward"
  928. ) }.tag(2)
  929. NavigationStack(path: self.$settingsPath) {
  930. Settings.RootView(resolver: resolver) }
  931. .tabItem { Label(
  932. "Settings",
  933. systemImage: "gear"
  934. ) }.tag(3)
  935. }
  936. .tint(Color.tabBar)
  937. Button(
  938. action: {
  939. state.showModal(for: .bolus) },
  940. label: {
  941. Image(systemName: "plus.circle.fill")
  942. .font(.system(size: 40))
  943. .foregroundStyle(Color.tabBar)
  944. .padding(.bottom, 1)
  945. .padding(.horizontal, 22.5)
  946. }
  947. )
  948. }.ignoresSafeArea(.keyboard, edges: .bottom).blur(radius: state.waitForSuggestion ? 8 : 0)
  949. .onChange(of: selectedTab) {
  950. print("current path is empty: \(settingsPath.isEmpty)")
  951. settingsPath = NavigationPath()
  952. }
  953. }
  954. var body: some View {
  955. ZStack(alignment: .center) {
  956. tabBar()
  957. if state.waitForSuggestion {
  958. CustomProgressView(text: "Updating IOB...")
  959. }
  960. }
  961. }
  962. // TODO: Consolidate all mmol parsing methods (in TagCloudView, NightscoutManager and HomeRootView) to one central func
  963. private func parseReasonConclusion(_ reasonConclusion: String, isMmolL _: Bool) -> String {
  964. let patterns = [
  965. "minGuardBG\\s*-?\\d+\\.?\\d*<-?\\d+\\.?\\d*",
  966. "Eventual BG\\s*-?\\d+\\.?\\d*\\s*>=\\s*-?\\d+\\.?\\d*",
  967. "\\S+\\s+-?\\d+\\.?\\d*\\s*>\\s*\\d+%\\s+of\\s+BG\\s+-?\\d+\\.?\\d*"
  968. ]
  969. let pattern = patterns.joined(separator: "|")
  970. let regex = try! NSRegularExpression(pattern: pattern)
  971. func convertToMmolL(_ value: String) -> String {
  972. if let glucoseValue = Double(value.replacingOccurrences(of: "[^\\d.-]", with: "", options: .regularExpression)) {
  973. let mmolValue = Decimal(glucoseValue).asMmolL
  974. return mmolValue.description
  975. }
  976. return value
  977. }
  978. let matches = regex.matches(
  979. in: reasonConclusion,
  980. range: NSRange(reasonConclusion.startIndex..., in: reasonConclusion)
  981. )
  982. var updatedConclusion = reasonConclusion
  983. for match in matches.reversed() {
  984. guard let range = Range(match.range, in: reasonConclusion) else { continue }
  985. let matchedString = String(reasonConclusion[range])
  986. if matchedString.contains("<") {
  987. // Handle "minGuardBG x<y" pattern
  988. let parts = matchedString.components(separatedBy: "<")
  989. if parts.count == 2,
  990. let firstValue = Double(
  991. parts[0]
  992. .components(separatedBy: CharacterSet(charactersIn: "0123456789.-").inverted).joined()
  993. ),
  994. let secondValue = Double(
  995. parts[1]
  996. .components(separatedBy: CharacterSet(charactersIn: "0123456789.-").inverted).joined()
  997. )
  998. {
  999. let formattedFirstValue = convertToMmolL(String(firstValue))
  1000. let formattedSecondValue = convertToMmolL(String(secondValue))
  1001. let formattedString = "minGuardBG \(formattedFirstValue)<\(formattedSecondValue)"
  1002. updatedConclusion.replaceSubrange(range, with: formattedString)
  1003. }
  1004. } else if matchedString.contains(">=") {
  1005. // Handle "Eventual BG x >= target" pattern
  1006. let parts = matchedString.components(separatedBy: " >= ")
  1007. if parts.count == 2,
  1008. let firstValue = Double(
  1009. parts[0]
  1010. .components(separatedBy: CharacterSet(charactersIn: "0123456789.-").inverted).joined()
  1011. ),
  1012. let secondValue = Double(
  1013. parts[1]
  1014. .components(separatedBy: CharacterSet(charactersIn: "0123456789.-").inverted).joined()
  1015. )
  1016. {
  1017. let formattedFirstValue = convertToMmolL(String(firstValue))
  1018. let formattedSecondValue = convertToMmolL(String(secondValue))
  1019. let formattedString = "Eventual BG \(formattedFirstValue) >= \(formattedSecondValue)"
  1020. updatedConclusion.replaceSubrange(range, with: formattedString)
  1021. }
  1022. } else if matchedString.contains(">") {
  1023. // Handle "maxDelta 37 > 20% of BG 95" style
  1024. let pattern = "(\\S+)\\s+(-?\\d+\\.?\\d*)\\s*>\\s*(\\d+)%\\s+of\\s+BG\\s+(-?\\d+\\.?\\d*)"
  1025. let localRegex = try! NSRegularExpression(pattern: pattern)
  1026. if let localMatch = localRegex.firstMatch(
  1027. in: matchedString,
  1028. range: NSRange(matchedString.startIndex..., in: matchedString)
  1029. ) {
  1030. let metric = String(matchedString[Range(localMatch.range(at: 1), in: matchedString)!])
  1031. let firstValue = String(matchedString[Range(localMatch.range(at: 2), in: matchedString)!])
  1032. let percentage = String(matchedString[Range(localMatch.range(at: 3), in: matchedString)!])
  1033. let bgValue = String(matchedString[Range(localMatch.range(at: 4), in: matchedString)!])
  1034. let formattedFirstValue = convertToMmolL(firstValue)
  1035. let formattedBGValue = convertToMmolL(bgValue)
  1036. let formattedString = "\(metric) \(formattedFirstValue) > \(percentage)% of BG \(formattedBGValue)"
  1037. updatedConclusion.replaceSubrange(range, with: formattedString)
  1038. }
  1039. }
  1040. }
  1041. return updatedConclusion.capitalizingFirstLetter()
  1042. }
  1043. private var popup: some View {
  1044. VStack(alignment: .leading, spacing: 4) {
  1045. Text(statusTitle).font(.headline).foregroundColor(.white)
  1046. .padding(.bottom, 4)
  1047. if let determination = state.determinationsFromPersistence.first {
  1048. if determination.glucose == 400 {
  1049. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  1050. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  1051. } else {
  1052. let tags = !state.isSmoothingEnabled ? determination.reasonParts : determination
  1053. .reasonParts + ["Smoothing: On"]
  1054. TagCloudView(
  1055. tags: tags,
  1056. shouldParseToMmolL: state.units == .mmolL
  1057. )
  1058. .animation(.none, value: false)
  1059. Text(
  1060. self
  1061. .parseReasonConclusion(
  1062. determination.reasonConclusion,
  1063. isMmolL: state.units == .mmolL
  1064. )
  1065. ).font(.caption).foregroundColor(.white)
  1066. }
  1067. } else {
  1068. Text("No determination found").font(.body).foregroundColor(.white)
  1069. }
  1070. if let errorMessage = state.errorMessage, let date = state.errorDate {
  1071. Text(NSLocalizedString("Error at", comment: "") + " " + Formatter.dateFormatter.string(from: date))
  1072. .foregroundColor(.white)
  1073. .font(.headline)
  1074. .padding(.bottom, 4)
  1075. .padding(.top, 8)
  1076. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  1077. }
  1078. }
  1079. }
  1080. private func setStatusTitle() {
  1081. if let determination = state.determinationsFromPersistence.first {
  1082. let dateFormatter = DateFormatter()
  1083. dateFormatter.timeStyle = .short
  1084. statusTitle = NSLocalizedString("Oref Determination enacted at", comment: "Headline in enacted pop up") +
  1085. " " +
  1086. dateFormatter
  1087. .string(from: determination.deliverAt ?? Date())
  1088. } else {
  1089. statusTitle = "No Oref determination"
  1090. return
  1091. }
  1092. }
  1093. }
  1094. }
  1095. extension UIDevice {
  1096. public enum DeviceSize: CGFloat {
  1097. case smallDevice = 667 // Height for 4" iPhone SE
  1098. case largeDevice = 852 // Height for 6.1" iPhone 15 Pro
  1099. }
  1100. @usableFromInline static func adjustPadding(
  1101. min: CGFloat? = nil,
  1102. max: CGFloat? = nil
  1103. ) -> CGFloat? {
  1104. if UIScreen.screenHeight > UIDevice.DeviceSize.smallDevice.rawValue {
  1105. if UIScreen.screenHeight >= UIDevice.DeviceSize.largeDevice.rawValue {
  1106. return max
  1107. } else {
  1108. return min != nil ?
  1109. (max != nil ? max! * (UIScreen.screenHeight / UIDevice.DeviceSize.largeDevice.rawValue) : nil) : nil
  1110. }
  1111. } else {
  1112. return min
  1113. }
  1114. }
  1115. }
  1116. extension UIScreen {
  1117. static var screenHeight: CGFloat {
  1118. UIScreen.main.bounds.height
  1119. }
  1120. static var screenWidth: CGFloat {
  1121. UIScreen.main.bounds.width
  1122. }
  1123. }
  1124. /// Checks if the device is using a 24-hour time format.
  1125. func is24HourFormat() -> Bool {
  1126. let formatter = DateFormatter()
  1127. formatter.locale = Locale.current
  1128. formatter.dateStyle = .none
  1129. formatter.timeStyle = .short
  1130. let dateString = formatter.string(from: Date())
  1131. return !dateString.contains("AM") && !dateString.contains("PM")
  1132. }
  1133. /// Converts a duration in minutes to a formatted string (e.g., "1 hr 30 min").
  1134. func formatHrMin(_ durationInMinutes: Int) -> String {
  1135. let hours = durationInMinutes / 60
  1136. let minutes = durationInMinutes % 60
  1137. switch (hours, minutes) {
  1138. case let (0, m):
  1139. return "\(m) min"
  1140. case let (h, 0):
  1141. return "\(h) hr"
  1142. default:
  1143. return "\(hours) hr \(minutes) min"
  1144. }
  1145. }
  1146. // Helper function to convert a start and end hour to either 24-hour or AM/PM format
  1147. func formatTimeRange(start: String?, end: String?) -> String {
  1148. guard let start = start, let end = end else {
  1149. return ""
  1150. }
  1151. // Check if the format is 24-hour or AM/PM
  1152. if is24HourFormat() {
  1153. // Return the original 24-hour format
  1154. return "\(start)-\(end)"
  1155. } else {
  1156. // Convert to AM/PM format using DateFormatter
  1157. let formatter = DateFormatter()
  1158. formatter.dateFormat = "HH"
  1159. if let startHour = Int(start), let endHour = Int(end) {
  1160. let startDate = Calendar.current.date(bySettingHour: startHour, minute: 0, second: 0, of: Date()) ?? Date()
  1161. let endDate = Calendar.current.date(bySettingHour: endHour, minute: 0, second: 0, of: Date()) ?? Date()
  1162. // Customize the format to "2p" or "2a"
  1163. formatter.dateFormat = "ha"
  1164. let startFormatted = formatter.string(from: startDate).lowercased().replacingOccurrences(of: "m", with: "")
  1165. let endFormatted = formatter.string(from: endDate).lowercased().replacingOccurrences(of: "m", with: "")
  1166. return "\(startFormatted)-\(endFormatted)"
  1167. } else {
  1168. return ""
  1169. }
  1170. }
  1171. }