HomeRootView.swift 54 KB

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