HomeRootView.swift 54 KB

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