HomeRootView.swift 55 KB

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