HomeRootView.swift 52 KB

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