DataTableRootView.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. import CoreData
  2. import SwiftUI
  3. import Swinject
  4. extension DataTable {
  5. struct RootView: BaseView {
  6. let resolver: Resolver
  7. @State var state = StateModel()
  8. @State private var isRemoveHistoryItemAlertPresented: Bool = false
  9. @State private var alertTitle: String = ""
  10. @State private var alertMessage: String = ""
  11. @State private var alertTreatmentToDelete: PumpEventStored?
  12. @State private var alertCarbEntryToDelete: CarbEntryStored?
  13. @State private var alertGlucoseToDelete: GlucoseStored?
  14. @State private var showAlert = false
  15. @State private var showFutureEntries: Bool = false // default to hide future entries
  16. @State private var showManualGlucose: Bool = false
  17. @State private var isAmountUnconfirmed: Bool = true
  18. @Environment(\.colorScheme) var colorScheme
  19. @Environment(\.managedObjectContext) var context
  20. @Environment(AppState.self) var appState
  21. @FetchRequest(
  22. entity: GlucoseStored.entity(),
  23. sortDescriptors: [NSSortDescriptor(keyPath: \GlucoseStored.date, ascending: false)],
  24. predicate: NSPredicate.predicateForOneDayAgo,
  25. animation: .bouncy
  26. ) var glucoseStored: FetchedResults<GlucoseStored>
  27. @FetchRequest(
  28. entity: PumpEventStored.entity(),
  29. sortDescriptors: [NSSortDescriptor(keyPath: \PumpEventStored.timestamp, ascending: false)],
  30. predicate: NSPredicate.pumpHistoryLast24h,
  31. animation: .bouncy
  32. ) var pumpEventStored: FetchedResults<PumpEventStored>
  33. @FetchRequest(
  34. entity: CarbEntryStored.entity(),
  35. sortDescriptors: [NSSortDescriptor(keyPath: \CarbEntryStored.date, ascending: false)],
  36. predicate: NSPredicate.carbsHistory,
  37. animation: .bouncy
  38. ) var carbEntryStored: FetchedResults<CarbEntryStored>
  39. @FetchRequest(
  40. entity: OverrideRunStored.entity(),
  41. sortDescriptors: [NSSortDescriptor(keyPath: \OverrideRunStored.startDate, ascending: false)],
  42. predicate: NSPredicate.overridesRunStoredFromOneDayAgo,
  43. animation: .bouncy
  44. ) var overrideRunStored: FetchedResults<OverrideRunStored>
  45. @FetchRequest(
  46. entity: TempTargetRunStored.entity(),
  47. sortDescriptors: [NSSortDescriptor(keyPath: \TempTargetRunStored.startDate, ascending: false)],
  48. predicate: NSPredicate.tempTargetRunStoredFromOneDayAgo,
  49. animation: .bouncy
  50. ) var tempTargetRunStored: FetchedResults<TempTargetRunStored>
  51. private var manualGlucoseFormatter: NumberFormatter {
  52. let formatter = NumberFormatter()
  53. formatter.numberStyle = .decimal
  54. formatter.maximumFractionDigits = 0
  55. if state.units == .mmolL {
  56. formatter.minimumFractionDigits = 0
  57. formatter.maximumFractionDigits = 1
  58. }
  59. formatter.roundingMode = .halfUp
  60. return formatter
  61. }
  62. var body: some View {
  63. ZStack(alignment: .center, content: {
  64. VStack {
  65. Picker("Mode", selection: $state.mode) {
  66. ForEach(
  67. Mode.allCases.indexed(),
  68. id: \.1
  69. ) { index, item in
  70. Text(item.name).tag(index)
  71. }
  72. }
  73. .pickerStyle(SegmentedPickerStyle())
  74. .padding(.horizontal)
  75. Form {
  76. switch state.mode {
  77. case .treatments: treatmentsList
  78. case .glucose: glucoseList
  79. case .meals: mealsList
  80. case .adjustments: adjustmentsList
  81. }
  82. }.scrollContentBackground(.hidden)
  83. .background(appState.trioBackgroundColor(for: colorScheme))
  84. }.blur(radius: state.waitForSuggestion ? 8 : 0)
  85. // Show custom progress view
  86. /// don't show it if glucose is stale as it will block the UI
  87. if state.waitForSuggestion && state.isGlucoseDataFresh(glucoseStored.first?.date) {
  88. CustomProgressView(text: progressText.rawValue)
  89. }
  90. })
  91. .background(appState.trioBackgroundColor(for: colorScheme))
  92. .onAppear(perform: configureView)
  93. .onDisappear {
  94. state.carbEntryDeleted = false
  95. state.insulinEntryDeleted = false
  96. }
  97. .navigationTitle("History")
  98. .navigationBarTitleDisplayMode(.large)
  99. .toolbar {
  100. ToolbarItem(placement: .topBarTrailing, content: {
  101. addButton({
  102. showManualGlucose = true
  103. state.manualGlucose = 0
  104. })
  105. })
  106. }
  107. .sheet(isPresented: $showManualGlucose) {
  108. addGlucoseView()
  109. }
  110. .sheet(isPresented: $state.showCarbEntryEditor) {
  111. if let carbEntry = state.carbEntryToEdit {
  112. CarbEntryEditorView(state: state, carbEntry: carbEntry)
  113. }
  114. }
  115. }
  116. @ViewBuilder func addButton(_ action: @escaping () -> Void) -> some View {
  117. Button(
  118. action: action,
  119. label: {
  120. HStack {
  121. Text("Add Glucose")
  122. Image(systemName: "plus")
  123. .font(.title2)
  124. }
  125. }
  126. )
  127. }
  128. private var progressText: ProgressText {
  129. switch (state.carbEntryDeleted, state.insulinEntryDeleted) {
  130. case (true, false):
  131. return .updatingCOB
  132. case(false, true):
  133. return .updatingIOB
  134. default:
  135. return .updatingHistory
  136. }
  137. }
  138. private var logGlucoseButton: some View {
  139. Button(
  140. action: {
  141. showManualGlucose = true
  142. state.manualGlucose = 0
  143. },
  144. label: {
  145. Text("Log Glucose")
  146. .foregroundColor(Color.accentColor)
  147. Image(systemName: "plus")
  148. .foregroundColor(Color.accentColor)
  149. }
  150. ).buttonStyle(.borderless)
  151. }
  152. private var treatmentsList: some View {
  153. List {
  154. HStack {
  155. Text("Insulin").foregroundStyle(.secondary)
  156. Spacer()
  157. Text("Time").foregroundStyle(.secondary)
  158. }
  159. if !pumpEventStored.isEmpty {
  160. ForEach(pumpEventStored.filter({ !showFutureEntries ? $0.timestamp ?? Date() <= Date() : true })) { item in
  161. treatmentView(item)
  162. }
  163. } else {
  164. ContentUnavailableView(
  165. "No data.",
  166. systemImage: "injection.needle"
  167. )
  168. }
  169. }.listRowBackground(Color.chart)
  170. }
  171. private var mealsList: some View {
  172. List {
  173. HStack {
  174. Text("Type").foregroundStyle(.secondary)
  175. Spacer()
  176. filterEntriesButton
  177. }
  178. if !carbEntryStored.isEmpty {
  179. ForEach(carbEntryStored.filter({ !showFutureEntries ? $0.date ?? Date() <= Date() : true })) { item in
  180. mealView(item)
  181. }
  182. } else {
  183. ContentUnavailableView(
  184. "No data.",
  185. systemImage: "fork.knife"
  186. )
  187. }
  188. }.listRowBackground(Color.chart)
  189. }
  190. private var adjustmentsList: some View {
  191. List {
  192. HStack {
  193. Text("Adjustment").foregroundStyle(.secondary)
  194. Spacer()
  195. }
  196. if !combinedAdjustments.isEmpty {
  197. ForEach(combinedAdjustments) { item in
  198. adjustmentView(for: item)
  199. }
  200. } else {
  201. ContentUnavailableView(
  202. "No data.",
  203. systemImage: "clock.arrow.2.circlepath"
  204. )
  205. }
  206. }
  207. .listRowBackground(Color.chart)
  208. }
  209. private var combinedAdjustments: [AdjustmentItem] {
  210. let overrides = overrideRunStored.map { override -> AdjustmentItem in
  211. AdjustmentItem(
  212. id: override.objectID,
  213. name: override.name ?? "Override",
  214. startDate: override.startDate ?? Date(),
  215. endDate: override.endDate ?? Date(),
  216. target: override.target?.decimalValue,
  217. type: .override
  218. )
  219. }
  220. let tempTargets = tempTargetRunStored.map { tempTarget -> AdjustmentItem in
  221. AdjustmentItem(
  222. id: tempTarget.objectID,
  223. name: tempTarget.name ?? "Temp Target",
  224. startDate: tempTarget.startDate ?? Date(),
  225. endDate: tempTarget.endDate ?? Date(),
  226. target: tempTarget.target?.decimalValue,
  227. type: .tempTarget
  228. )
  229. }
  230. let combined = overrides + tempTargets
  231. return combined.sorted(by: { $0.startDate > $1.startDate })
  232. }
  233. private struct AdjustmentItem: Identifiable {
  234. let id: NSManagedObjectID
  235. let name: String
  236. let startDate: Date
  237. let endDate: Date
  238. let target: Decimal?
  239. let type: AdjustmentType
  240. }
  241. private enum AdjustmentType {
  242. case override
  243. case tempTarget
  244. var symbolName: String {
  245. switch self {
  246. case .override:
  247. return "clock.arrow.2.circlepath"
  248. case .tempTarget:
  249. return "target"
  250. }
  251. }
  252. var symbolColor: Color {
  253. switch self {
  254. case .override:
  255. return .orange
  256. case .tempTarget:
  257. return .blue
  258. }
  259. }
  260. }
  261. @ViewBuilder private func adjustmentView(for item: AdjustmentItem) -> some View {
  262. let formattedDates =
  263. "\(Formatter.dateFormatter.string(from: item.startDate)) - \(Formatter.dateFormatter.string(from: item.endDate))"
  264. let targetDescription: String = {
  265. guard let target = item.target, target != 0 else {
  266. return ""
  267. }
  268. return "\(state.units == .mgdL ? target : target.asMmolL) \(state.units.rawValue)"
  269. }()
  270. let labels: [String] = [
  271. targetDescription,
  272. formattedDates
  273. ].filter { !$0.isEmpty }
  274. ZStack(alignment: .trailing) {
  275. HStack {
  276. VStack(alignment: .leading) {
  277. HStack {
  278. Image(systemName: item.type.symbolName)
  279. .foregroundStyle(item.type == .override ? Color.purple : Color.green)
  280. Text(item.name)
  281. .font(.headline)
  282. Spacer()
  283. }
  284. HStack(spacing: 5) {
  285. ForEach(labels, id: \.self) { label in
  286. Text(label)
  287. if label != labels.last {
  288. Divider()
  289. }
  290. }
  291. Spacer()
  292. }
  293. .padding(.top, 2)
  294. .foregroundColor(.secondary)
  295. .font(.caption)
  296. }
  297. .contentShape(Rectangle())
  298. }
  299. }
  300. .padding(.vertical, 8)
  301. }
  302. private var glucoseList: some View {
  303. List {
  304. HStack {
  305. Text("Values").foregroundStyle(.secondary)
  306. Spacer()
  307. Text("Time").foregroundStyle(.secondary)
  308. }
  309. if !glucoseStored.isEmpty {
  310. ForEach(glucoseStored) { glucose in
  311. HStack {
  312. Text(formatGlucose(Decimal(glucose.glucose), isManual: glucose.isManual))
  313. /// check for manual glucose
  314. if glucose.isManual {
  315. Image(systemName: "drop.fill").symbolRenderingMode(.monochrome).foregroundStyle(.red)
  316. } else {
  317. Text("\(glucose.directionEnum?.symbol ?? "--")")
  318. }
  319. Spacer()
  320. Text(Formatter.dateFormatter.string(from: glucose.date ?? Date()))
  321. }.swipeActions {
  322. Button(
  323. "Delete",
  324. systemImage: "trash.fill",
  325. role: .none,
  326. action: {
  327. alertGlucoseToDelete = glucose
  328. alertTitle = "Delete Glucose?"
  329. alertMessage = Formatter.dateFormatter
  330. .string(from: glucose.date ?? Date()) + ", " +
  331. (Formatter.decimalFormatterWithTwoFractionDigits.string(for: glucose.glucose) ?? "0")
  332. isRemoveHistoryItemAlertPresented = true
  333. }
  334. ).tint(.red)
  335. }
  336. .alert(
  337. Text(NSLocalizedString(alertTitle, comment: "")),
  338. isPresented: $isRemoveHistoryItemAlertPresented
  339. ) {
  340. Button("Cancel", role: .cancel) {}
  341. Button("Delete", role: .destructive) {
  342. guard let glucoseToDelete = alertGlucoseToDelete else {
  343. debug(.default, "Cannot gracefully unwrap alertCarbEntryToDelete!")
  344. return
  345. }
  346. let glucoseToDeleteObjectID = glucoseToDelete.objectID
  347. state.invokeGlucoseDeletionTask(glucoseToDeleteObjectID)
  348. }
  349. } message: {
  350. Text("\n" + NSLocalizedString(alertMessage, comment: ""))
  351. }
  352. }
  353. } else {
  354. ContentUnavailableView(
  355. "No data.",
  356. systemImage: "drop.fill"
  357. )
  358. }
  359. }.listRowBackground(Color.chart)
  360. .alert(isPresented: $showAlert) {
  361. Alert(title: Text("Error"), message: Text(alertMessage), dismissButton: .default(Text("OK")))
  362. }
  363. }
  364. private func deleteGlucose(at offsets: IndexSet) {
  365. for index in offsets {
  366. let glucoseToDelete = glucoseStored[index]
  367. context.delete(glucoseToDelete)
  368. }
  369. do {
  370. try context.save()
  371. debugPrint("Data Table Root View: \(#function) \(DebuggingIdentifiers.succeeded) deleted glucose from core data")
  372. } catch {
  373. debugPrint(
  374. "Data Table Root View: \(#function) \(DebuggingIdentifiers.failed) error while deleting glucose from core data"
  375. )
  376. alertMessage = "Failed to delete glucose data: \(error.localizedDescription)"
  377. showAlert = true
  378. }
  379. }
  380. @ViewBuilder private func addGlucoseView() -> some View {
  381. let limitLow: Decimal = state.units == .mmolL ? 0.8 : 14
  382. let limitHigh: Decimal = state.units == .mmolL ? 40 : 720
  383. NavigationView {
  384. VStack {
  385. Form {
  386. Section {
  387. HStack {
  388. Text("New Glucose")
  389. TextFieldWithToolBar(
  390. text: $state.manualGlucose,
  391. placeholder: " ... ",
  392. shouldBecomeFirstResponder: true,
  393. numberFormatter: manualGlucoseFormatter
  394. )
  395. Text(state.units.rawValue).foregroundStyle(.secondary)
  396. }
  397. }.listRowBackground(Color.chart)
  398. Section {
  399. HStack {
  400. Button {
  401. state.addManualGlucose()
  402. isAmountUnconfirmed = false
  403. showManualGlucose = false
  404. state.mode = .glucose
  405. }
  406. label: { Text("Save") }
  407. .frame(maxWidth: .infinity, alignment: .center)
  408. .disabled(state.manualGlucose < limitLow || state.manualGlucose > limitHigh)
  409. }
  410. }
  411. .listRowBackground(
  412. state.manualGlucose < limitLow || state
  413. .manualGlucose > limitHigh ? Color(.systemGray4) : Color(.systemBlue)
  414. )
  415. .tint(.white)
  416. }.scrollContentBackground(.hidden).background(appState.trioBackgroundColor(for: colorScheme))
  417. }
  418. .onAppear(perform: configureView)
  419. .navigationTitle("Add Glucose")
  420. .navigationBarTitleDisplayMode(.inline)
  421. .toolbar {
  422. ToolbarItem(placement: .topBarLeading) {
  423. Button("Close") {
  424. showManualGlucose = false
  425. }
  426. }
  427. }
  428. }
  429. }
  430. private var filterEntriesButton: some View {
  431. Button(action: { showFutureEntries.toggle() }, label: {
  432. HStack {
  433. Text(showFutureEntries ? "Hide Future" : "Show Future")
  434. .foregroundColor(Color.secondary)
  435. Image(systemName: showFutureEntries ? "calendar.badge.minus" : "calendar.badge.plus")
  436. }.frame(maxWidth: .infinity, alignment: .trailing)
  437. }).buttonStyle(.borderless)
  438. }
  439. @ViewBuilder private func treatmentView(_ item: PumpEventStored) -> some View {
  440. HStack {
  441. if let bolus = item.bolus, let amount = bolus.amount {
  442. Image(systemName: "circle.fill").foregroundColor(Color.insulin)
  443. Text(bolus.isSMB ? "SMB" : item.type ?? "Bolus")
  444. Text(
  445. (Formatter.decimalFormatterWithTwoFractionDigits.string(from: amount) ?? "0") +
  446. NSLocalizedString(" U", comment: "Insulin unit")
  447. )
  448. .foregroundColor(.secondary)
  449. if bolus.isExternal {
  450. Text(NSLocalizedString("External", comment: "External Insulin")).foregroundColor(.secondary)
  451. }
  452. } else if let tempBasal = item.tempBasal, let rate = tempBasal.rate {
  453. Image(systemName: "circle.fill").foregroundColor(Color.insulin.opacity(0.4))
  454. Text("Temp Basal")
  455. Text(
  456. (Formatter.decimalFormatterWithTwoFractionDigits.string(from: rate) ?? "0") +
  457. NSLocalizedString(" U/hr", comment: "Unit insulin per hour")
  458. )
  459. .foregroundColor(.secondary)
  460. if tempBasal.duration > 0 {
  461. Text("\(tempBasal.duration.string) min").foregroundColor(.secondary)
  462. }
  463. } else {
  464. Image(systemName: "circle.fill").foregroundColor(Color.loopGray)
  465. Text(item.type ?? "Pump Event")
  466. }
  467. Spacer()
  468. Text(Formatter.dateFormatter.string(from: item.timestamp ?? Date())).moveDisabled(true)
  469. }
  470. .swipeActions {
  471. if item.bolus != nil {
  472. Button(
  473. "Delete",
  474. systemImage: "trash.fill",
  475. role: .none,
  476. action: {
  477. alertTreatmentToDelete = item
  478. alertTitle = "Delete Insulin?"
  479. alertMessage = Formatter.dateFormatter
  480. .string(from: item.timestamp ?? Date()) + ", " +
  481. (Formatter.decimalFormatterWithTwoFractionDigits.string(from: item.bolus?.amount ?? 0) ?? "0") +
  482. NSLocalizedString(" U", comment: "Insulin unit")
  483. if let bolus = item.bolus {
  484. // Add text snippet, so that alert message is more descriptive for SMBs
  485. alertMessage += bolus.isSMB ? " SMB" : ""
  486. }
  487. isRemoveHistoryItemAlertPresented = true
  488. }
  489. ).tint(.red)
  490. }
  491. }
  492. .alert(
  493. Text(NSLocalizedString(alertTitle, comment: "")),
  494. isPresented: $isRemoveHistoryItemAlertPresented
  495. ) {
  496. Button("Cancel", role: .cancel) {}
  497. Button("Delete", role: .destructive) {
  498. guard let treatmentToDelete = alertTreatmentToDelete else {
  499. debug(.default, "Cannot gracefully unwrap alertTreatmentToDelete!")
  500. return
  501. }
  502. let treatmentObjectID = treatmentToDelete.objectID
  503. state.invokeInsulinDeletionTask(treatmentObjectID)
  504. }
  505. } message: {
  506. Text("\n" + NSLocalizedString(alertMessage, comment: ""))
  507. }
  508. }
  509. @ViewBuilder private func mealView(_ meal: CarbEntryStored) -> some View {
  510. VStack {
  511. HStack {
  512. if meal.isFPU {
  513. Image(systemName: "circle.fill").foregroundColor(Color.orange.opacity(0.5))
  514. Text("Fat / Protein")
  515. Text(
  516. (Formatter.decimalFormatterWithTwoFractionDigits.string(for: meal.carbs) ?? "0") +
  517. NSLocalizedString(" g", comment: "gram of carbs")
  518. )
  519. } else {
  520. Image(systemName: "circle.fill").foregroundColor(Color.loopYellow)
  521. Text("Carbs")
  522. Text(
  523. (Formatter.decimalFormatterWithTwoFractionDigits.string(for: meal.carbs) ?? "0") +
  524. NSLocalizedString(" g", comment: "gram of carb equilvalents")
  525. )
  526. }
  527. Spacer()
  528. Text(Formatter.dateFormatter.string(from: meal.date ?? Date()))
  529. .moveDisabled(true)
  530. }
  531. if let note = meal.note, note != "" {
  532. HStack {
  533. Image(systemName: "square.and.pencil")
  534. Text(note)
  535. Spacer()
  536. }.padding(.top, 5).foregroundColor(.secondary)
  537. }
  538. }
  539. .swipeActions {
  540. Button(
  541. "Delete",
  542. systemImage: "trash.fill",
  543. role: .none,
  544. action: {
  545. alertCarbEntryToDelete = meal
  546. // meal is carb-only
  547. if meal.fpuID == nil {
  548. alertTitle = "Delete Carbs?"
  549. alertMessage = Formatter.dateFormatter
  550. .string(from: meal.date ?? Date()) + ", " +
  551. (Formatter.decimalFormatterWithTwoFractionDigits.string(for: meal.carbs) ?? "0") +
  552. NSLocalizedString(" g", comment: "gram of carbs")
  553. }
  554. // meal is complex-meal or fpu-only
  555. else {
  556. alertTitle = meal.isFPU ? "Delete Carbs Equivalents?" : "Delete Carbs?"
  557. alertMessage = "All FPUs and the carbs of the meal will be deleted."
  558. }
  559. isRemoveHistoryItemAlertPresented = true
  560. }
  561. ).tint(.red)
  562. Button(
  563. "Edit",
  564. systemImage: "pencil",
  565. role: .none,
  566. action: {
  567. state.carbEntryToEdit = meal
  568. state.showCarbEntryEditor = true
  569. }
  570. )
  571. .tint(!state.settingsManager.settings.useFPUconversion && meal.isFPU ? Color(.systemGray4) : Color.blue)
  572. .disabled(!state.settingsManager.settings.useFPUconversion && meal.isFPU)
  573. }
  574. .alert(
  575. Text(NSLocalizedString(alertTitle, comment: "")),
  576. isPresented: $isRemoveHistoryItemAlertPresented
  577. ) {
  578. Button("Cancel", role: .cancel) {}
  579. Button("Delete", role: .destructive) {
  580. guard let carbEntryToDelete = alertCarbEntryToDelete else {
  581. debug(.default, "Cannot gracefully unwrap alertCarbEntryToDelete!")
  582. return
  583. }
  584. let treatmentObjectID = carbEntryToDelete.objectID
  585. state.invokeCarbDeletionTask(
  586. treatmentObjectID,
  587. isFpuOrComplexMeal: carbEntryToDelete.isFPU || carbEntryToDelete.fat > 0 || carbEntryToDelete.protein > 0
  588. )
  589. }
  590. } message: {
  591. Text("\n" + NSLocalizedString(alertMessage, comment: ""))
  592. }
  593. }
  594. // MARK: - Format glucose
  595. private func formatGlucose(_ value: Decimal, isManual: Bool) -> String {
  596. let formatter = isManual ? manualGlucoseFormatter : Formatter.glucoseFormatter(for: state.units)
  597. let glucoseValue = state.units == .mmolL ? value.asMmolL : value
  598. let formattedValue = formatter.string(from: glucoseValue as NSNumber) ?? "--"
  599. return formattedValue
  600. }
  601. }
  602. }