HomeRootView.swift 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  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: Text(
  864. "Forecasts future glucose readings based on the amount of insulin still active in the body."
  865. ),
  866. color: .insulin
  867. )
  868. DefinitionRow(
  869. term: "ZT (Zero-Temp)",
  870. definition: Text(
  871. "Forecasts the worst-case future glucose reading scenario if no carbs are absorbed and insulin delivery is stopped until glucose starts rising."
  872. ),
  873. color: .zt
  874. )
  875. DefinitionRow(
  876. term: "COB (Carbs on Board)",
  877. definition: Text(
  878. "Forecasts future glucose reading changes by considering the amount of carbohydrates still being absorbed in the body."
  879. ),
  880. color: .loopYellow
  881. )
  882. DefinitionRow(
  883. term: "UAM (Unannounced Meal)",
  884. definition: Text(
  885. "Forecasts future glucose levels and insulin dosing needs for unexpected meals or other causes of glucose reading increases without prior notice."
  886. ),
  887. color: .uam
  888. )
  889. }
  890. .padding(.trailing, 10)
  891. .navigationBarTitle("Legend", displayMode: .inline)
  892. }
  893. @ViewBuilder func legendConeOfUncertaintyView() -> some View {
  894. List {
  895. DefinitionRow(
  896. term: "Cone of Uncertainty",
  897. definition: VStack {
  898. Text(
  899. "For simplicity reasons, oref's various forecast curves are displayed as a \"Cone of Uncertainty\" that depicts a possible, forecasted range of future glucose fluctuation based on the current data and the algothim's result."
  900. )
  901. Text(
  902. "Note: To modify the forecast display type, go to Trio Settings > Features > User Interface > Forecast Display Type."
  903. )
  904. },
  905. color: Color.blue.opacity(0.5)
  906. )
  907. }
  908. .padding(.trailing, 10)
  909. .navigationBarTitle("Legend", displayMode: .inline)
  910. }
  911. @ViewBuilder func tabBar() -> some View {
  912. ZStack(alignment: .bottom) {
  913. TabView(selection: $selectedTab) {
  914. let carbsRequiredBadge: String? = {
  915. guard let carbsRequired = state.enactedAndNonEnactedDeterminations.first?.carbsRequired,
  916. state.showCarbsRequiredBadge
  917. else {
  918. return nil
  919. }
  920. let carbsRequiredDecimal = Decimal(carbsRequired)
  921. if carbsRequiredDecimal > state.settingsManager.settings.carbsRequiredThreshold {
  922. let numberAsNSNumber = NSDecimalNumber(decimal: carbsRequiredDecimal)
  923. return (Formatter.decimalFormatterWithTwoFractionDigits.string(from: numberAsNSNumber) ?? "") + " g"
  924. }
  925. return nil
  926. }()
  927. NavigationStack { mainView() }
  928. .tabItem { Label("Main", systemImage: "chart.xyaxis.line") }
  929. .badge(carbsRequiredBadge).tag(0)
  930. NavigationStack { DataTable.RootView(resolver: resolver) }
  931. .tabItem { Label("History", systemImage: historySFSymbol) }.tag(1)
  932. Spacer()
  933. NavigationStack { Adjustments.RootView(resolver: resolver) }
  934. .tabItem {
  935. Label(
  936. "Adjustments",
  937. systemImage: "slider.horizontal.2.gobackward"
  938. ) }.tag(2)
  939. NavigationStack(path: self.$settingsPath) {
  940. Settings.RootView(resolver: resolver) }
  941. .tabItem { Label(
  942. "Settings",
  943. systemImage: "gear"
  944. ) }.tag(3)
  945. }
  946. .tint(Color.tabBar)
  947. Button(
  948. action: {
  949. state.showModal(for: .bolus) },
  950. label: {
  951. Image(systemName: "plus.circle.fill")
  952. .font(.system(size: 40))
  953. .foregroundStyle(Color.tabBar)
  954. .padding(.bottom, 1)
  955. .padding(.horizontal, 20)
  956. }
  957. )
  958. }.ignoresSafeArea(.keyboard, edges: .bottom).blur(radius: state.waitForSuggestion ? 8 : 0)
  959. .onChange(of: selectedTab) {
  960. print("current path is empty: \(settingsPath.isEmpty)")
  961. settingsPath = NavigationPath()
  962. }
  963. }
  964. var body: some View {
  965. ZStack(alignment: .center) {
  966. tabBar()
  967. if state.waitForSuggestion {
  968. CustomProgressView(text: "Updating IOB...")
  969. }
  970. }
  971. }
  972. // TODO: Consolidate all mmol parsing methods (in TagCloudView, NightscoutManager and HomeRootView) to one central func
  973. private func parseReasonConclusion(_ reasonConclusion: String, isMmolL _: Bool) -> String {
  974. let patterns = [
  975. "minGuardBG\\s*-?\\d+\\.?\\d*<-?\\d+\\.?\\d*",
  976. "Eventual BG\\s*-?\\d+\\.?\\d*\\s*>=\\s*-?\\d+\\.?\\d*",
  977. "\\S+\\s+-?\\d+\\.?\\d*\\s*>\\s*\\d+%\\s+of\\s+BG\\s+-?\\d+\\.?\\d*"
  978. ]
  979. let pattern = patterns.joined(separator: "|")
  980. let regex = try! NSRegularExpression(pattern: pattern)
  981. func convertToMmolL(_ value: String) -> String {
  982. if let glucoseValue = Double(value.replacingOccurrences(of: "[^\\d.-]", with: "", options: .regularExpression)) {
  983. let mmolValue = Decimal(glucoseValue).asMmolL
  984. return mmolValue.description
  985. }
  986. return value
  987. }
  988. let matches = regex.matches(
  989. in: reasonConclusion,
  990. range: NSRange(reasonConclusion.startIndex..., in: reasonConclusion)
  991. )
  992. var updatedConclusion = reasonConclusion
  993. for match in matches.reversed() {
  994. guard let range = Range(match.range, in: reasonConclusion) else { continue }
  995. let matchedString = String(reasonConclusion[range])
  996. if matchedString.contains("<") {
  997. // Handle "minGuardBG x<y" pattern
  998. let parts = matchedString.components(separatedBy: "<")
  999. if parts.count == 2,
  1000. let firstValue = Double(
  1001. parts[0]
  1002. .components(separatedBy: CharacterSet(charactersIn: "0123456789.-").inverted).joined()
  1003. ),
  1004. let secondValue = Double(
  1005. parts[1]
  1006. .components(separatedBy: CharacterSet(charactersIn: "0123456789.-").inverted).joined()
  1007. )
  1008. {
  1009. let formattedFirstValue = convertToMmolL(String(firstValue))
  1010. let formattedSecondValue = convertToMmolL(String(secondValue))
  1011. let formattedString = "minGuardBG \(formattedFirstValue)<\(formattedSecondValue)"
  1012. updatedConclusion.replaceSubrange(range, with: formattedString)
  1013. }
  1014. } else if matchedString.contains(">=") {
  1015. // Handle "Eventual BG x >= target" pattern
  1016. let parts = matchedString.components(separatedBy: " >= ")
  1017. if parts.count == 2,
  1018. let firstValue = Double(
  1019. parts[0]
  1020. .components(separatedBy: CharacterSet(charactersIn: "0123456789.-").inverted).joined()
  1021. ),
  1022. let secondValue = Double(
  1023. parts[1]
  1024. .components(separatedBy: CharacterSet(charactersIn: "0123456789.-").inverted).joined()
  1025. )
  1026. {
  1027. let formattedFirstValue = convertToMmolL(String(firstValue))
  1028. let formattedSecondValue = convertToMmolL(String(secondValue))
  1029. let formattedString = "Eventual BG \(formattedFirstValue) >= \(formattedSecondValue)"
  1030. updatedConclusion.replaceSubrange(range, with: formattedString)
  1031. }
  1032. } else if matchedString.contains(">") {
  1033. // Handle "maxDelta 37 > 20% of BG 95" style
  1034. let pattern = "(\\S+)\\s+(-?\\d+\\.?\\d*)\\s*>\\s*(\\d+)%\\s+of\\s+BG\\s+(-?\\d+\\.?\\d*)"
  1035. let localRegex = try! NSRegularExpression(pattern: pattern)
  1036. if let localMatch = localRegex.firstMatch(
  1037. in: matchedString,
  1038. range: NSRange(matchedString.startIndex..., in: matchedString)
  1039. ) {
  1040. let metric = String(matchedString[Range(localMatch.range(at: 1), in: matchedString)!])
  1041. let firstValue = String(matchedString[Range(localMatch.range(at: 2), in: matchedString)!])
  1042. let percentage = String(matchedString[Range(localMatch.range(at: 3), in: matchedString)!])
  1043. let bgValue = String(matchedString[Range(localMatch.range(at: 4), in: matchedString)!])
  1044. let formattedFirstValue = convertToMmolL(firstValue)
  1045. let formattedBGValue = convertToMmolL(bgValue)
  1046. let formattedString = "\(metric) \(formattedFirstValue) > \(percentage)% of BG \(formattedBGValue)"
  1047. updatedConclusion.replaceSubrange(range, with: formattedString)
  1048. }
  1049. }
  1050. }
  1051. return updatedConclusion.capitalizingFirstLetter()
  1052. }
  1053. private var popup: some View {
  1054. VStack(alignment: .leading, spacing: 4) {
  1055. Text(statusTitle).font(.headline).foregroundColor(.white)
  1056. .padding(.bottom, 4)
  1057. if let determination = state.determinationsFromPersistence.first {
  1058. if determination.glucose == 400 {
  1059. Text("Invalid CGM reading (HIGH).").font(.callout).bold().foregroundColor(.loopRed).padding(.top, 8)
  1060. Text("SMBs and High Temps Disabled.").font(.caption).foregroundColor(.white).padding(.bottom, 4)
  1061. } else {
  1062. let tags = !state.isSmoothingEnabled ? determination.reasonParts : determination
  1063. .reasonParts + ["Smoothing: On"]
  1064. TagCloudView(
  1065. tags: tags,
  1066. shouldParseToMmolL: state.units == .mmolL
  1067. )
  1068. .animation(.none, value: false)
  1069. Text(
  1070. self
  1071. .parseReasonConclusion(
  1072. determination.reasonConclusion,
  1073. isMmolL: state.units == .mmolL
  1074. )
  1075. ).font(.caption).foregroundColor(.white)
  1076. }
  1077. } else {
  1078. Text("No determination found").font(.body).foregroundColor(.white)
  1079. }
  1080. if let errorMessage = state.errorMessage, let date = state.errorDate {
  1081. Text(NSLocalizedString("Error at", comment: "") + " " + Formatter.dateFormatter.string(from: date))
  1082. .foregroundColor(.white)
  1083. .font(.headline)
  1084. .padding(.bottom, 4)
  1085. .padding(.top, 8)
  1086. Text(errorMessage).font(.caption).foregroundColor(.loopRed)
  1087. }
  1088. }
  1089. }
  1090. private func setStatusTitle() {
  1091. if let determination = state.determinationsFromPersistence.first {
  1092. let dateFormatter = DateFormatter()
  1093. dateFormatter.timeStyle = .short
  1094. statusTitle = NSLocalizedString("Oref Determination enacted at", comment: "Headline in enacted pop up") +
  1095. " " +
  1096. dateFormatter
  1097. .string(from: determination.deliverAt ?? Date())
  1098. } else {
  1099. statusTitle = "No Oref determination"
  1100. return
  1101. }
  1102. }
  1103. }
  1104. }
  1105. extension UIDevice {
  1106. public enum DeviceSize: CGFloat {
  1107. case smallDevice = 667 // Height for 4" iPhone SE
  1108. case largeDevice = 852 // Height for 6.1" iPhone 15 Pro
  1109. }
  1110. @usableFromInline static func adjustPadding(
  1111. min: CGFloat? = nil,
  1112. max: CGFloat? = nil
  1113. ) -> CGFloat? {
  1114. if UIScreen.screenHeight > UIDevice.DeviceSize.smallDevice.rawValue {
  1115. if UIScreen.screenHeight >= UIDevice.DeviceSize.largeDevice.rawValue {
  1116. return max
  1117. } else {
  1118. return min != nil ?
  1119. (max != nil ? max! * (UIScreen.screenHeight / UIDevice.DeviceSize.largeDevice.rawValue) : nil) : nil
  1120. }
  1121. } else {
  1122. return min
  1123. }
  1124. }
  1125. }
  1126. extension UIScreen {
  1127. static var screenHeight: CGFloat {
  1128. UIScreen.main.bounds.height
  1129. }
  1130. static var screenWidth: CGFloat {
  1131. UIScreen.main.bounds.width
  1132. }
  1133. }
  1134. /// Checks if the device is using a 24-hour time format.
  1135. func is24HourFormat() -> Bool {
  1136. let formatter = DateFormatter()
  1137. formatter.locale = Locale.current
  1138. formatter.dateStyle = .none
  1139. formatter.timeStyle = .short
  1140. let dateString = formatter.string(from: Date())
  1141. return !dateString.contains("AM") && !dateString.contains("PM")
  1142. }
  1143. /// Converts a duration in minutes to a formatted string (e.g., "1 hr 30 min").
  1144. func formatHrMin(_ durationInMinutes: Int) -> String {
  1145. let hours = durationInMinutes / 60
  1146. let minutes = durationInMinutes % 60
  1147. switch (hours, minutes) {
  1148. case let (0, m):
  1149. return "\(m) min"
  1150. case let (h, 0):
  1151. return "\(h) hr"
  1152. default:
  1153. return "\(hours) hr \(minutes) min"
  1154. }
  1155. }
  1156. // Helper function to convert a start and end hour to either 24-hour or AM/PM format
  1157. func formatTimeRange(start: String?, end: String?) -> String {
  1158. guard let start = start, let end = end else {
  1159. return ""
  1160. }
  1161. // Check if the format is 24-hour or AM/PM
  1162. if is24HourFormat() {
  1163. // Return the original 24-hour format
  1164. return "\(start)-\(end)"
  1165. } else {
  1166. // Convert to AM/PM format using DateFormatter
  1167. let formatter = DateFormatter()
  1168. formatter.dateFormat = "HH"
  1169. if let startHour = Int(start), let endHour = Int(end) {
  1170. let startDate = Calendar.current.date(bySettingHour: startHour, minute: 0, second: 0, of: Date()) ?? Date()
  1171. let endDate = Calendar.current.date(bySettingHour: endHour, minute: 0, second: 0, of: Date()) ?? Date()
  1172. // Customize the format to "2p" or "2a"
  1173. formatter.dateFormat = "ha"
  1174. let startFormatted = formatter.string(from: startDate).lowercased().replacingOccurrences(of: "m", with: "")
  1175. let endFormatted = formatter.string(from: endDate).lowercased().replacingOccurrences(of: "m", with: "")
  1176. return "\(startFormatted)-\(endFormatted)"
  1177. } else {
  1178. return ""
  1179. }
  1180. }
  1181. }