LiveActivity.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. .overlay(alignment: .topTrailing) {
  91. if detailedViewState.isOverrideActive {
  92. HStack {
  93. Text("\(detailedViewState.overrideName)")
  94. .font(.footnote)
  95. .fontWeight(.bold)
  96. .foregroundStyle(.white)
  97. }
  98. .padding(6)
  99. .background {
  100. RoundedRectangle(cornerRadius: 10)
  101. .fill(Color.purple.opacity(colorScheme == .dark ? 0.6 : 0.8))
  102. }
  103. }
  104. }
  105. HStack {
  106. ForEach(context.state.itemOrder, id: \.self) { item in
  107. switch item {
  108. case "currentGlucose":
  109. if context.state.showCurrentGlucose {
  110. VStack {
  111. LiveActivityBGLabelView(context: context, additionalState: detailedViewState)
  112. HStack {
  113. LiveActivityGlucoseDeltaLabelView(context: context)
  114. if !context.isStale, let direction = context.state.direction {
  115. Text(direction).font(.headline)
  116. }
  117. }
  118. }
  119. }
  120. case "iob":
  121. if context.state.showIOB {
  122. LiveActivityIOBLabelView(context: context, additionalState: detailedViewState)
  123. }
  124. case "cob":
  125. if context.state.showCOB {
  126. LiveActivityCOBLabelView(context: context, additionalState: detailedViewState)
  127. }
  128. case "updatedLabel":
  129. if context.state.showUpdatedLabel {
  130. LiveActivityUpdatedLabelView(context: context, isDetailedLayout: true)
  131. }
  132. default:
  133. EmptyView()
  134. }
  135. Divider().foregroundStyle(.primary).fontWeight(.bold).frame(width: 10)
  136. }
  137. }
  138. }
  139. .privacySensitive()
  140. .padding(.all, 14)
  141. .foregroundStyle(Color.primary)
  142. .activityBackgroundTint(colorScheme == .light ? Color.white.opacity(0.43) : Color.black.opacity(0.43))
  143. } else {
  144. HStack(spacing: 3) {
  145. LiveActivityBGAndTrendView(context: context, size: .expanded).font(.title)
  146. Spacer()
  147. VStack(alignment: .trailing, spacing: 5) {
  148. LiveActivityGlucoseDeltaLabelView(context: context).font(.title3)
  149. LiveActivityUpdatedLabelView(context: context, isDetailedLayout: false).font(.caption)
  150. .foregroundStyle(.primary.opacity(0.7))
  151. }
  152. }
  153. .privacySensitive()
  154. .padding(.all, 15)
  155. .foregroundStyle(Color.primary)
  156. .activityBackgroundTint(colorScheme == .light ? Color.white.opacity(0.43) : Color.black.opacity(0.43))
  157. }
  158. }
  159. }
  160. // Separate the smaller sections into reusable views
  161. struct LiveActivityBGAndTrendView: View {
  162. var context: ActivityViewContext<LiveActivityAttributes>
  163. fileprivate var size: Size
  164. var body: some View {
  165. let (view, _) = bgAndTrend(context: context, size: size)
  166. return view
  167. }
  168. }
  169. struct LiveActivityBGLabelView: View {
  170. var context: ActivityViewContext<LiveActivityAttributes>
  171. var additionalState: LiveActivityAttributes.ContentAdditionalState
  172. var body: some View {
  173. Text(context.state.bg)
  174. .fontWeight(.bold)
  175. .font(.title3)
  176. .strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  177. }
  178. }
  179. struct LiveActivityGlucoseDeltaLabelView: View {
  180. var context: ActivityViewContext<LiveActivityAttributes>
  181. var body: some View {
  182. if !context.state.change.isEmpty {
  183. Text(context.state.change).foregroundStyle(.primary).font(.subheadline)
  184. .strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  185. } else {
  186. Text("--")
  187. }
  188. }
  189. }
  190. struct LiveActivityIOBLabelView: View {
  191. var context: ActivityViewContext<LiveActivityAttributes>
  192. var additionalState: LiveActivityAttributes.ContentAdditionalState
  193. private var bolusFormatter: NumberFormatter {
  194. let formatter = NumberFormatter()
  195. formatter.numberStyle = .decimal
  196. formatter.maximumFractionDigits = 1
  197. formatter.decimalSeparator = "."
  198. return formatter
  199. }
  200. var body: some View {
  201. VStack(spacing: 2) {
  202. HStack {
  203. Text(
  204. bolusFormatter.string(from: additionalState.iob as NSNumber) ?? "--"
  205. ).fontWeight(.bold).font(.title3).strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  206. Text("U").foregroundStyle(.primary).font(.headline).fontWeight(.bold)
  207. }
  208. Text("IOB").font(.subheadline).foregroundStyle(.primary)
  209. }
  210. }
  211. }
  212. struct LiveActivityCOBLabelView: View {
  213. var context: ActivityViewContext<LiveActivityAttributes>
  214. var additionalState: LiveActivityAttributes.ContentAdditionalState
  215. var body: some View {
  216. VStack(spacing: 2) {
  217. HStack {
  218. Text(
  219. "\(additionalState.cob)"
  220. ).fontWeight(.bold).font(.title3).strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  221. Text("g").foregroundStyle(.primary).font(.headline).fontWeight(.bold)
  222. }
  223. Text("COB").font(.subheadline).foregroundStyle(.primary)
  224. }
  225. }
  226. }
  227. struct LiveActivityUpdatedLabelView: View {
  228. var context: ActivityViewContext<LiveActivityAttributes>
  229. var isDetailedLayout: Bool
  230. private var dateFormatter: DateFormatter {
  231. let formatter = DateFormatter()
  232. formatter.dateStyle = .none
  233. formatter.timeStyle = .short
  234. return formatter
  235. }
  236. var body: some View {
  237. if isDetailedLayout {
  238. let dateText = Text("\(dateFormatter.string(from: context.state.date))").font(.title3)
  239. .foregroundStyle(.primary)
  240. VStack {
  241. if context.isStale {
  242. if #available(iOSApplicationExtension 17.0, *) {
  243. dateText.bold().foregroundStyle(.red)
  244. } else {
  245. dateText.bold().foregroundColor(.red)
  246. }
  247. } else {
  248. if #available(iOSApplicationExtension 17.0, *) {
  249. dateText.bold().foregroundStyle(.primary)
  250. } else {
  251. dateText.bold().foregroundColor(.primary)
  252. }
  253. }
  254. Text("Updated").font(.subheadline).foregroundStyle(.primary)
  255. }
  256. } else {
  257. let dateText = Text("\(dateFormatter.string(from: context.state.date))").font(.subheadline)
  258. .foregroundStyle(.secondary)
  259. HStack {
  260. Text("Updated:").font(.subheadline).foregroundStyle(.secondary)
  261. if context.isStale {
  262. if #available(iOSApplicationExtension 17.0, *) {
  263. dateText.bold().foregroundStyle(.red)
  264. } else {
  265. dateText.bold().foregroundColor(.red)
  266. }
  267. } else {
  268. if #available(iOSApplicationExtension 17.0, *) {
  269. dateText.bold().foregroundStyle(.primary)
  270. } else {
  271. dateText.bold().foregroundColor(.primary)
  272. }
  273. }
  274. }
  275. }
  276. }
  277. }
  278. struct LiveActivityChartView: View {
  279. var context: ActivityViewContext<LiveActivityAttributes>
  280. var additionalState: LiveActivityAttributes.ContentAdditionalState
  281. var body: some View {
  282. // Determine scale
  283. let minValue = min(additionalState.chart.min() ?? 39, 39) as Decimal
  284. let maxValue = max(additionalState.chart.max() ?? 300, 300) as Decimal
  285. let yAxisRuleMarkMin = additionalState.unit == "mg/dL" ? additionalState.lowGlucose : additionalState.lowGlucose
  286. .asMmolL
  287. let yAxisRuleMarkMax = additionalState.unit == "mg/dL" ? additionalState.highGlucose : additionalState.highGlucose
  288. .asMmolL
  289. let target = additionalState.unit == "mg/dL" ? additionalState.target : additionalState.target.asMmolL
  290. let calendar = Calendar.current
  291. let now = Date()
  292. let startDate = calendar.date(byAdding: .hour, value: -6, to: now) ?? now
  293. let endDate = calendar.date(byAdding: .hour, value: 2, to: now) ?? now
  294. Chart {
  295. RuleMark(y: .value("Low", yAxisRuleMarkMin))
  296. .lineStyle(.init(lineWidth: 0.5, dash: [5]))
  297. RuleMark(y: .value("High", yAxisRuleMarkMax))
  298. .lineStyle(.init(lineWidth: 0.5, dash: [5]))
  299. RuleMark(y: .value("Target", target)).foregroundStyle(.green.gradient).lineStyle(.init(lineWidth: 1))
  300. if context.state.detailedViewState?.isOverrideActive == true {
  301. drawActiveOverrides()
  302. }
  303. drawChart(yAxisRuleMarkMin: yAxisRuleMarkMin, yAxisRuleMarkMax: yAxisRuleMarkMax)
  304. }
  305. .chartYAxis {
  306. AxisMarks(position: .trailing) { _ in
  307. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.white)
  308. AxisValueLabel().foregroundStyle(.primary).font(.footnote)
  309. }
  310. }
  311. .chartYScale(domain: additionalState.unit == "mg/dL" ? minValue ... maxValue : minValue.asMmolL ... maxValue.asMmolL)
  312. .chartYAxis(.hidden)
  313. .chartPlotStyle { plotContent in
  314. plotContent
  315. .background(
  316. RoundedRectangle(cornerRadius: 12)
  317. .fill(Color.clear)
  318. )
  319. .clipShape(RoundedRectangle(cornerRadius: 12))
  320. }
  321. .chartXScale(domain: startDate ... endDate)
  322. .chartXAxis {
  323. AxisMarks(position: .automatic) { _ in
  324. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.white)
  325. }
  326. }
  327. }
  328. private func drawActiveOverrides() -> some ChartContent {
  329. let start: Date = context.state.detailedViewState?.overrideDate ?? .distantPast
  330. let duration = context.state.detailedViewState?.overrideDuration ?? 0
  331. let durationAsTimeInterval = TimeInterval((duration as NSDecimalNumber).doubleValue * 60) // return seconds
  332. let end: Date = start.addingTimeInterval(durationAsTimeInterval)
  333. let target = context.state.detailedViewState?.overrideTarget ?? 0
  334. return RuleMark(
  335. xStart: .value("Start", start, unit: .second),
  336. xEnd: .value("End", end, unit: .second),
  337. y: .value("Value", target)
  338. )
  339. .foregroundStyle(Color.purple.opacity(0.6))
  340. .lineStyle(.init(lineWidth: 8))
  341. }
  342. private func drawChart(yAxisRuleMarkMin: Decimal, yAxisRuleMarkMax: Decimal) -> some ChartContent {
  343. ForEach(additionalState.chart.indices, id: \.self) { index in
  344. let currentValue = additionalState.chart[index]
  345. let displayValue = additionalState.unit == "mg/dL" ? currentValue : currentValue.asMmolL
  346. let chartDate = additionalState.chartDate[index] ?? Date()
  347. let pointMark = PointMark(
  348. x: .value("Time", chartDate),
  349. y: .value("Value", displayValue)
  350. ).symbolSize(15)
  351. if displayValue > yAxisRuleMarkMax {
  352. pointMark.foregroundStyle(Color.orange.gradient)
  353. } else if displayValue < yAxisRuleMarkMin {
  354. pointMark.foregroundStyle(Color.red.gradient)
  355. } else {
  356. pointMark.foregroundStyle(Color.green.gradient)
  357. }
  358. }
  359. }
  360. }
  361. // Expanded, minimal, compact view components
  362. struct LiveActivityExpandedLeadingView: View {
  363. var context: ActivityViewContext<LiveActivityAttributes>
  364. var body: some View {
  365. LiveActivityBGAndTrendView(context: context, size: .expanded).font(.title2).padding(.leading, 5)
  366. }
  367. }
  368. struct LiveActivityExpandedTrailingView: View {
  369. var context: ActivityViewContext<LiveActivityAttributes>
  370. var body: some View {
  371. LiveActivityGlucoseDeltaLabelView(context: context).font(.title2).padding(.trailing, 5)
  372. }
  373. }
  374. struct LiveActivityExpandedBottomView: View {
  375. var context: ActivityViewContext<LiveActivityAttributes>
  376. var body: some View {
  377. if context.state.isInitialState {
  378. Text("Live Activity Expired. Open Trio to Refresh")
  379. } else if let detailedViewState = context.state.detailedViewState {
  380. LiveActivityChartView(context: context, additionalState: detailedViewState)
  381. }
  382. }
  383. }
  384. struct LiveActivityExpandedCenterView: View {
  385. var context: ActivityViewContext<LiveActivityAttributes>
  386. var body: some View {
  387. LiveActivityUpdatedLabelView(context: context, isDetailedLayout: false).font(.caption).foregroundStyle(Color.secondary)
  388. }
  389. }
  390. struct LiveActivityCompactLeadingView: View {
  391. var context: ActivityViewContext<LiveActivityAttributes>
  392. var body: some View {
  393. LiveActivityBGAndTrendView(context: context, size: .compact).padding(.leading, 4)
  394. }
  395. }
  396. struct LiveActivityCompactTrailingView: View {
  397. var context: ActivityViewContext<LiveActivityAttributes>
  398. var body: some View {
  399. LiveActivityGlucoseDeltaLabelView(context: context).padding(.trailing, 4)
  400. }
  401. }
  402. struct LiveActivityMinimalView: View {
  403. var context: ActivityViewContext<LiveActivityAttributes>
  404. var body: some View {
  405. let (label, characterCount) = bgAndTrend(context: context, size: .minimal)
  406. let adjustedLabel = label.padding(.leading, 7).padding(.trailing, 3)
  407. if characterCount < 4 {
  408. adjustedLabel
  409. } else if characterCount < 5 {
  410. adjustedLabel.fontWidth(.condensed)
  411. } else {
  412. adjustedLabel.fontWidth(.compressed)
  413. }
  414. }
  415. }
  416. // Helper function for bgAndTrend logic
  417. private func bgAndTrend(context: ActivityViewContext<LiveActivityAttributes>, size _: Size) -> (some View, Int) {
  418. var characters = 0
  419. let bgText = context.state.bg
  420. characters += bgText.count
  421. var directionText: String?
  422. if let direction = context.state.direction {
  423. directionText = direction
  424. characters += directionText!.count
  425. }
  426. let stack = HStack {
  427. Text(bgText)
  428. if let direction = directionText {
  429. Text(direction)
  430. }
  431. }
  432. return (stack, characters)
  433. }