HomeRootView.swift 54 KB

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