LiveActivity.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. import ActivityKit
  2. import Charts
  3. import SwiftUI
  4. import WidgetKit
  5. private enum Size {
  6. case minimal
  7. case compact
  8. case expanded
  9. }
  10. enum GlucoseUnits: String, Equatable {
  11. case mgdL = "mg/dL"
  12. case mmolL = "mmol/L"
  13. static let exchangeRate: Decimal = 0.0555
  14. }
  15. func rounded(_ value: Decimal, scale: Int, roundingMode: NSDecimalNumber.RoundingMode) -> Decimal {
  16. var result = Decimal()
  17. var toRound = value
  18. NSDecimalRound(&result, &toRound, scale, roundingMode)
  19. return result
  20. }
  21. extension Int {
  22. var asMmolL: Decimal {
  23. rounded(Decimal(self) * GlucoseUnits.exchangeRate, scale: 1, roundingMode: .plain)
  24. }
  25. var formattedAsMmolL: String {
  26. NumberFormatter.glucoseFormatter.string(from: asMmolL as NSDecimalNumber) ?? "\(asMmolL)"
  27. }
  28. }
  29. extension Decimal {
  30. var asMmolL: Decimal {
  31. rounded(self * GlucoseUnits.exchangeRate, scale: 1, roundingMode: .plain)
  32. }
  33. var asMgdL: Decimal {
  34. rounded(self / GlucoseUnits.exchangeRate, scale: 0, roundingMode: .plain)
  35. }
  36. var formattedAsMmolL: String {
  37. NumberFormatter.glucoseFormatter.string(from: asMmolL as NSDecimalNumber) ?? "\(asMmolL)"
  38. }
  39. }
  40. extension NumberFormatter {
  41. static let glucoseFormatter: NumberFormatter = {
  42. let formatter = NumberFormatter()
  43. formatter.locale = Locale.current
  44. formatter.numberStyle = .decimal
  45. formatter.minimumFractionDigits = 1
  46. formatter.maximumFractionDigits = 1
  47. return formatter
  48. }()
  49. }
  50. extension Color {
  51. static let systemBackground = Color(UIColor.systemBackground)
  52. }
  53. struct LiveActivity: Widget {
  54. var body: some WidgetConfiguration {
  55. ActivityConfiguration(for: LiveActivityAttributes.self) { context in
  56. LiveActivityView(context: context)
  57. } dynamicIsland: { context in
  58. DynamicIsland {
  59. DynamicIslandExpandedRegion(.leading) {
  60. LiveActivityExpandedLeadingView(context: context)
  61. }
  62. DynamicIslandExpandedRegion(.trailing) {
  63. LiveActivityExpandedTrailingView(context: context)
  64. }
  65. DynamicIslandExpandedRegion(.bottom) {
  66. LiveActivityExpandedBottomView(context: context)
  67. }
  68. DynamicIslandExpandedRegion(.center) {
  69. LiveActivityExpandedCenterView(context: context)
  70. }
  71. } compactLeading: {
  72. LiveActivityCompactLeadingView(context: context)
  73. } compactTrailing: {
  74. LiveActivityCompactTrailingView(context: context)
  75. } minimal: {
  76. LiveActivityMinimalView(context: context)
  77. }
  78. }
  79. }
  80. }
  81. struct LiveActivityView: View {
  82. @Environment(\.colorScheme) var colorScheme
  83. var context: ActivityViewContext<LiveActivityAttributes>
  84. var body: some View {
  85. if let detailedViewState = context.state.detailedViewState {
  86. VStack {
  87. LiveActivityChartView(context: context, additionalState: detailedViewState)
  88. .frame(maxWidth: UIScreen.main.bounds.width * 0.9)
  89. .frame(height: 80)
  90. HStack {
  91. ForEach(context.state.itemOrder, id: \.self) { item in
  92. switch item {
  93. case "currentGlucose":
  94. if context.state.showCurrentGlucose {
  95. VStack {
  96. LiveActivityBGLabelView(context: context, additionalState: detailedViewState)
  97. HStack {
  98. LiveActivityGlucoseDeltaLabelView(context: context)
  99. if !context.isStale, let direction = context.state.direction {
  100. Text(direction).font(.headline)
  101. }
  102. }
  103. }
  104. }
  105. case "iob":
  106. if context.state.showIOB {
  107. LiveActivityIOBLabelView(context: context, additionalState: detailedViewState)
  108. }
  109. case "cob":
  110. if context.state.showCOB {
  111. LiveActivityCOBLabelView(context: context, additionalState: detailedViewState)
  112. }
  113. case "updatedLabel":
  114. if context.state.showUpdatedLabel {
  115. LiveActivityUpdatedLabelView(context: context, isDetailedLayout: true)
  116. }
  117. default:
  118. EmptyView()
  119. }
  120. Divider().foregroundStyle(.primary).fontWeight(.bold).frame(width: 10)
  121. }
  122. }
  123. }
  124. .privacySensitive()
  125. .padding(.all, 14)
  126. .foregroundStyle(Color.primary)
  127. .activityBackgroundTint(colorScheme == .light ? Color.white.opacity(0.43) : Color.black.opacity(0.43))
  128. } else {
  129. HStack(spacing: 3) {
  130. LiveActivityBGAndTrendView(context: context, size: .expanded).font(.title)
  131. Spacer()
  132. VStack(alignment: .trailing, spacing: 5) {
  133. LiveActivityGlucoseDeltaLabelView(context: context).font(.title3)
  134. LiveActivityUpdatedLabelView(context: context, isDetailedLayout: false).font(.caption)
  135. .foregroundStyle(.primary.opacity(0.7))
  136. }
  137. }
  138. .privacySensitive()
  139. .padding(.all, 15)
  140. .foregroundStyle(Color.primary)
  141. .activityBackgroundTint(colorScheme == .light ? Color.white.opacity(0.43) : Color.black.opacity(0.43))
  142. }
  143. }
  144. }
  145. // Separate the smaller sections into reusable views
  146. struct LiveActivityBGAndTrendView: View {
  147. var context: ActivityViewContext<LiveActivityAttributes>
  148. fileprivate var size: Size
  149. var body: some View {
  150. let (view, _) = bgAndTrend(context: context, size: size)
  151. return view
  152. }
  153. }
  154. struct LiveActivityBGLabelView: View {
  155. var context: ActivityViewContext<LiveActivityAttributes>
  156. var additionalState: LiveActivityAttributes.ContentAdditionalState
  157. var body: some View {
  158. Text(context.state.bg)
  159. .fontWeight(.bold)
  160. .font(.title3)
  161. .strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  162. }
  163. }
  164. struct LiveActivityGlucoseDeltaLabelView: View {
  165. var context: ActivityViewContext<LiveActivityAttributes>
  166. var body: some View {
  167. if !context.state.change.isEmpty {
  168. Text(context.state.change).foregroundStyle(.primary).font(.subheadline)
  169. .strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  170. } else {
  171. Text("--")
  172. }
  173. }
  174. }
  175. struct LiveActivityIOBLabelView: View {
  176. var context: ActivityViewContext<LiveActivityAttributes>
  177. var additionalState: LiveActivityAttributes.ContentAdditionalState
  178. private var bolusFormatter: NumberFormatter {
  179. let formatter = NumberFormatter()
  180. formatter.numberStyle = .decimal
  181. formatter.maximumFractionDigits = 1
  182. formatter.decimalSeparator = "."
  183. return formatter
  184. }
  185. var body: some View {
  186. VStack(spacing: 2) {
  187. HStack {
  188. Text(
  189. bolusFormatter.string(from: additionalState.iob as NSNumber) ?? "--"
  190. ).fontWeight(.bold).font(.title3).strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  191. Text("U").foregroundStyle(.primary).font(.headline).fontWeight(.bold)
  192. }
  193. Text("IOB").font(.subheadline).foregroundStyle(.primary)
  194. }
  195. }
  196. }
  197. struct LiveActivityCOBLabelView: View {
  198. var context: ActivityViewContext<LiveActivityAttributes>
  199. var additionalState: LiveActivityAttributes.ContentAdditionalState
  200. var body: some View {
  201. VStack(spacing: 2) {
  202. HStack {
  203. Text(
  204. "\(additionalState.cob)"
  205. ).fontWeight(.bold).font(.title3).strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  206. Text("g").foregroundStyle(.primary).font(.headline).fontWeight(.bold)
  207. }
  208. Text("COB").font(.subheadline).foregroundStyle(.primary)
  209. }
  210. }
  211. }
  212. struct LiveActivityUpdatedLabelView: View {
  213. var context: ActivityViewContext<LiveActivityAttributes>
  214. var isDetailedLayout: Bool
  215. private var dateFormatter: DateFormatter {
  216. let formatter = DateFormatter()
  217. formatter.dateStyle = .none
  218. formatter.timeStyle = .short
  219. return formatter
  220. }
  221. var body: some View {
  222. if isDetailedLayout {
  223. let dateText = Text("\(dateFormatter.string(from: context.state.date))").font(.title3)
  224. .foregroundStyle(.primary)
  225. VStack {
  226. if context.isStale {
  227. if #available(iOSApplicationExtension 17.0, *) {
  228. dateText.bold().foregroundStyle(.red)
  229. } else {
  230. dateText.bold().foregroundColor(.red)
  231. }
  232. } else {
  233. if #available(iOSApplicationExtension 17.0, *) {
  234. dateText.bold().foregroundStyle(.primary)
  235. } else {
  236. dateText.bold().foregroundColor(.primary)
  237. }
  238. }
  239. Text("Updated").font(.subheadline).foregroundStyle(.primary)
  240. }
  241. } else {
  242. let dateText = Text("\(dateFormatter.string(from: context.state.date))").font(.subheadline)
  243. .foregroundStyle(.secondary)
  244. HStack {
  245. Text("Updated:").font(.subheadline).foregroundStyle(.secondary)
  246. if context.isStale {
  247. if #available(iOSApplicationExtension 17.0, *) {
  248. dateText.bold().foregroundStyle(.red)
  249. } else {
  250. dateText.bold().foregroundColor(.red)
  251. }
  252. } else {
  253. if #available(iOSApplicationExtension 17.0, *) {
  254. dateText.bold().foregroundStyle(.primary)
  255. } else {
  256. dateText.bold().foregroundColor(.primary)
  257. }
  258. }
  259. }
  260. }
  261. }
  262. }
  263. struct LiveActivityChartView: View {
  264. var context: ActivityViewContext<LiveActivityAttributes>
  265. var additionalState: LiveActivityAttributes.ContentAdditionalState
  266. var body: some View {
  267. if context.isStale {
  268. Text("No data available")
  269. } else {
  270. // Determine scale
  271. let minValue = min(additionalState.chart.min() ?? 45, 40) - 20
  272. let maxValue = max(additionalState.chart.max() ?? 270, 300) + 50
  273. let yAxisRuleMarkMin = additionalState.unit == "mg/dL" ? additionalState.lowGlucose : additionalState.lowGlucose
  274. .asMmolL
  275. let yAxisRuleMarkMax = additionalState.unit == "mg/dL" ? additionalState.highGlucose : additionalState.highGlucose
  276. .asMmolL
  277. let target = additionalState.unit == "mg/dL" ? additionalState.target : additionalState.target.asMmolL
  278. Chart {
  279. RuleMark(y: .value("Low", yAxisRuleMarkMin))
  280. .lineStyle(.init(lineWidth: 0.5, dash: [5]))
  281. RuleMark(y: .value("High", yAxisRuleMarkMax))
  282. .lineStyle(.init(lineWidth: 0.5, dash: [5]))
  283. RuleMark(y: .value("Target", target)).foregroundStyle(.green.gradient).lineStyle(.init(lineWidth: 1))
  284. ForEach(additionalState.chart.indices, id: \.self) { index in
  285. let currentValue = additionalState.chart[index]
  286. let displayValue = additionalState.unit == "mg/dL" ? currentValue : currentValue.asMmolL
  287. let chartDate = additionalState.chartDate[index] ?? Date()
  288. let pointMark = PointMark(
  289. x: .value("Time", chartDate),
  290. y: .value("Value", displayValue)
  291. ).symbolSize(15)
  292. if displayValue > yAxisRuleMarkMax {
  293. pointMark.foregroundStyle(Color.orange.gradient)
  294. } else if displayValue < yAxisRuleMarkMin {
  295. pointMark.foregroundStyle(Color.red.gradient)
  296. } else {
  297. pointMark.foregroundStyle(Color.green.gradient)
  298. }
  299. }
  300. }
  301. .chartYAxis {
  302. AxisMarks(position: .trailing) { _ in
  303. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.white)
  304. AxisValueLabel().foregroundStyle(.primary).font(.footnote)
  305. }
  306. }
  307. .chartYScale(domain: additionalState.unit == "mg/dL" ? minValue ... maxValue : minValue.asMmolL ... maxValue.asMmolL)
  308. .chartYAxis(.hidden)
  309. .chartPlotStyle { plotContent in
  310. plotContent
  311. .background(
  312. RoundedRectangle(cornerRadius: 12)
  313. .fill(Color.clear)
  314. )
  315. .clipShape(RoundedRectangle(cornerRadius: 12))
  316. }
  317. .chartXAxis {
  318. AxisMarks(position: .automatic) { _ in
  319. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.white)
  320. }
  321. }
  322. }
  323. }
  324. }
  325. // Expanded, minimal, compact view components
  326. struct LiveActivityExpandedLeadingView: View {
  327. var context: ActivityViewContext<LiveActivityAttributes>
  328. var body: some View {
  329. LiveActivityBGAndTrendView(context: context, size: .expanded).font(.title2).padding(.leading, 5)
  330. }
  331. }
  332. struct LiveActivityExpandedTrailingView: View {
  333. var context: ActivityViewContext<LiveActivityAttributes>
  334. var body: some View {
  335. LiveActivityGlucoseDeltaLabelView(context: context).font(.title2).padding(.trailing, 5)
  336. }
  337. }
  338. struct LiveActivityExpandedBottomView: View {
  339. var context: ActivityViewContext<LiveActivityAttributes>
  340. var body: some View {
  341. if context.state.isInitialState {
  342. Text("Live Activity Expired. Open Trio to Refresh")
  343. } else if let detailedViewState = context.state.detailedViewState {
  344. LiveActivityChartView(context: context, additionalState: detailedViewState)
  345. }
  346. }
  347. }
  348. struct LiveActivityExpandedCenterView: View {
  349. var context: ActivityViewContext<LiveActivityAttributes>
  350. var body: some View {
  351. LiveActivityUpdatedLabelView(context: context, isDetailedLayout: false).font(.caption).foregroundStyle(Color.secondary)
  352. }
  353. }
  354. struct LiveActivityCompactLeadingView: View {
  355. var context: ActivityViewContext<LiveActivityAttributes>
  356. var body: some View {
  357. LiveActivityBGAndTrendView(context: context, size: .compact).padding(.leading, 4)
  358. }
  359. }
  360. struct LiveActivityCompactTrailingView: View {
  361. var context: ActivityViewContext<LiveActivityAttributes>
  362. var body: some View {
  363. LiveActivityGlucoseDeltaLabelView(context: context).padding(.trailing, 4)
  364. }
  365. }
  366. struct LiveActivityMinimalView: View {
  367. var context: ActivityViewContext<LiveActivityAttributes>
  368. var body: some View {
  369. let (label, characterCount) = bgAndTrend(context: context, size: .minimal)
  370. let adjustedLabel = label.padding(.leading, 7).padding(.trailing, 3)
  371. if characterCount < 4 {
  372. adjustedLabel
  373. } else if characterCount < 5 {
  374. adjustedLabel.fontWidth(.condensed)
  375. } else {
  376. adjustedLabel.fontWidth(.compressed)
  377. }
  378. }
  379. }
  380. // Helper function for bgAndTrend logic
  381. private func bgAndTrend(context: ActivityViewContext<LiveActivityAttributes>, size _: Size) -> (some View, Int) {
  382. var characters = 0
  383. let bgText = context.state.bg
  384. characters += bgText.count
  385. var directionText: String?
  386. if let direction = context.state.direction {
  387. directionText = direction
  388. characters += directionText!.count
  389. }
  390. let stack = HStack {
  391. Text(bgText)
  392. if let direction = directionText {
  393. Text(direction)
  394. }
  395. }
  396. return (stack, characters)
  397. }