HomeRootView.swift 53 KB

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