HomeRootView.swift 54 KB

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