HomeRootView.swift 54 KB

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