HomeRootView.swift 55 KB

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