HomeRootView.swift 55 KB

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