HomeRootView.swift 55 KB

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