LiveActivity.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. import ActivityKit
  2. import Charts
  3. import Foundation
  4. import SwiftUI
  5. import WidgetKit
  6. private enum Size {
  7. case minimal
  8. case compact
  9. case expanded
  10. }
  11. enum GlucoseUnits: String, Equatable {
  12. case mgdL = "mg/dL"
  13. case mmolL = "mmol/L"
  14. static let exchangeRate: Decimal = 0.0555
  15. }
  16. func rounded(_ value: Decimal, scale: Int, roundingMode: NSDecimalNumber.RoundingMode) -> Decimal {
  17. var result = Decimal()
  18. var toRound = value
  19. NSDecimalRound(&result, &toRound, scale, roundingMode)
  20. return result
  21. }
  22. extension Int {
  23. var asMmolL: Decimal {
  24. rounded(Decimal(self) * GlucoseUnits.exchangeRate, scale: 1, roundingMode: .plain)
  25. }
  26. var formattedAsMmolL: String {
  27. NumberFormatter.glucoseFormatter.string(from: asMmolL as NSDecimalNumber) ?? "\(asMmolL)"
  28. }
  29. }
  30. extension Decimal {
  31. var asMmolL: Decimal {
  32. rounded(self * GlucoseUnits.exchangeRate, scale: 1, roundingMode: .plain)
  33. }
  34. var asMgdL: Decimal {
  35. rounded(self / GlucoseUnits.exchangeRate, scale: 0, roundingMode: .plain)
  36. }
  37. var formattedAsMmolL: String {
  38. NumberFormatter.glucoseFormatter.string(from: asMmolL as NSDecimalNumber) ?? "\(asMmolL)"
  39. }
  40. }
  41. extension NumberFormatter {
  42. static let glucoseFormatter: NumberFormatter = {
  43. let formatter = NumberFormatter()
  44. formatter.locale = Locale.current
  45. formatter.numberStyle = .decimal
  46. formatter.minimumFractionDigits = 1
  47. formatter.maximumFractionDigits = 1
  48. return formatter
  49. }()
  50. }
  51. struct LiveActivity: Widget {
  52. private let dateFormatter: DateFormatter = {
  53. var f = DateFormatter()
  54. f.dateStyle = .none
  55. f.timeStyle = .short
  56. return f
  57. }()
  58. private var bolusFormatter: NumberFormatter {
  59. let formatter = NumberFormatter()
  60. formatter.numberStyle = .decimal
  61. formatter.maximumFractionDigits = 1
  62. formatter.decimalSeparator = "."
  63. return formatter
  64. }
  65. private var carbsFormatter: NumberFormatter {
  66. let formatter = NumberFormatter()
  67. formatter.numberStyle = .decimal
  68. formatter.maximumFractionDigits = 0
  69. return formatter
  70. }
  71. @ViewBuilder private func changeLabel(context: ActivityViewContext<LiveActivityAttributes>) -> some View {
  72. HStack(spacing: -5) {
  73. if !context.state.change.isEmpty {
  74. Text(context.state.change).foregroundStyle(.primary).font(.subheadline)
  75. .strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  76. } else {
  77. Text("--")
  78. }
  79. }
  80. }
  81. @ViewBuilder func cobLabel(
  82. context: ActivityViewContext<LiveActivityAttributes>,
  83. additionalState: LiveActivityAttributes.ContentAdditionalState
  84. ) -> some View {
  85. VStack(spacing: 2) {
  86. HStack {
  87. Text(
  88. carbsFormatter.string(from: additionalState.cob as NSNumber) ?? "--"
  89. ).fontWeight(.bold).font(.title3).strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  90. Text(NSLocalizedString("g", comment: "grams of carbs")).foregroundStyle(.primary).font(.headline)
  91. .fontWeight(.bold)
  92. }
  93. Text("COB").font(.subheadline).foregroundStyle(.primary)
  94. }
  95. }
  96. @ViewBuilder func iobLabel(
  97. context: ActivityViewContext<LiveActivityAttributes>,
  98. additionalState: LiveActivityAttributes.ContentAdditionalState
  99. ) -> some View {
  100. VStack(spacing: 2) {
  101. HStack {
  102. Text(
  103. bolusFormatter.string(from: additionalState.iob as NSNumber) ?? "--"
  104. ).font(.title3).fontWeight(.bold).strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  105. Text(NSLocalizedString("U", comment: "Unit in number of units delivered (keep the space character!)"))
  106. .foregroundStyle(.primary).font(.headline).fontWeight(.bold)
  107. }
  108. Text("IOB").font(.subheadline).foregroundStyle(.primary)
  109. }
  110. }
  111. @ViewBuilder func mealLabel(
  112. context: ActivityViewContext<LiveActivityAttributes>,
  113. additionalState: LiveActivityAttributes.ContentAdditionalState
  114. ) -> some View {
  115. HStack {
  116. VStack(alignment: .leading, spacing: 0, content: {
  117. HStack {
  118. Image(systemName: "fork.knife")
  119. .font(.title3)
  120. .foregroundColor(.yellow)
  121. }
  122. HStack {
  123. Image(systemName: "syringe.fill")
  124. .font(.title3)
  125. .foregroundColor(.blue)
  126. }
  127. })
  128. VStack(alignment: .trailing, spacing: 0, content: {
  129. HStack {
  130. Text(
  131. carbsFormatter.string(from: additionalState.cob as NSNumber) ?? "--"
  132. ).fontWeight(.bold).font(.title3).strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  133. Text(NSLocalizedString(" g", comment: "grams of carbs")).foregroundStyle(.primary).font(.headline)
  134. }
  135. HStack {
  136. Text(
  137. bolusFormatter.string(from: additionalState.iob as NSNumber) ?? "--"
  138. ).font(.title3).fontWeight(.bold).strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  139. Text(NSLocalizedString(" U", comment: "Unit in number of units delivered (keep the space character!)"))
  140. .foregroundStyle(.primary).font(.headline)
  141. }
  142. })
  143. VStack(alignment: .trailing, spacing: 1, content: {
  144. if additionalState.isOverrideActive {
  145. Image(systemName: "person.crop.circle.fill.badge.checkmark")
  146. .font(.title3)
  147. }
  148. })
  149. }
  150. }
  151. @ViewBuilder func trend(context: ActivityViewContext<LiveActivityAttributes>) -> some View {
  152. if context.isStale {
  153. Text("--")
  154. } else {
  155. if let trendSystemImage = context.state.direction {
  156. Image(systemName: trendSystemImage)
  157. }
  158. }
  159. }
  160. private func expiredLabel() -> some View {
  161. Text("Live Activity Expired. Open Trio to Refresh")
  162. .minimumScaleFactor(0.01)
  163. }
  164. @ViewBuilder private func updatedLabel(context: ActivityViewContext<LiveActivityAttributes>) -> some View {
  165. VStack {
  166. let dateText = Text("\(dateFormatter.string(from: context.state.date))").font(.title3).foregroundStyle(.primary)
  167. if context.isStale {
  168. if #available(iOSApplicationExtension 17.0, *) {
  169. dateText.bold().foregroundStyle(.red)
  170. } else {
  171. dateText.bold().foregroundColor(.red)
  172. }
  173. } else {
  174. if #available(iOSApplicationExtension 17.0, *) {
  175. dateText.bold().foregroundStyle(.primary)
  176. } else {
  177. dateText.bold().foregroundColor(.primary)
  178. }
  179. }
  180. Text("Updated").font(.subheadline).foregroundStyle(.primary)
  181. }
  182. }
  183. @ViewBuilder private func bgLabel(
  184. context: ActivityViewContext<LiveActivityAttributes>,
  185. additionalState _: LiveActivityAttributes.ContentAdditionalState
  186. ) -> some View {
  187. HStack(alignment: .center) {
  188. Text(context.state.bg)
  189. .fontWeight(.bold)
  190. .font(.title3)
  191. .strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  192. }
  193. }
  194. private func bgAndTrend(context: ActivityViewContext<LiveActivityAttributes>, size: Size) -> (some View, Int) {
  195. var characters = 0
  196. let bgText = context.state.bg
  197. characters += bgText.count
  198. // narrow mode is for the minimal dynamic island view
  199. // there is not enough space to show all three arrow there
  200. // and everything has to be squeezed together to some degree
  201. // only display the first arrow character and make it red in case there were more characters
  202. var directionText: String?
  203. var warnColor: Color?
  204. if let direction = context.state.direction {
  205. if size == .compact {
  206. directionText = String(direction[direction.startIndex ... direction.startIndex])
  207. if direction.count > 1 {
  208. warnColor = Color.red
  209. }
  210. } else {
  211. directionText = direction
  212. }
  213. characters += directionText!.count
  214. }
  215. let spacing: CGFloat
  216. switch size {
  217. case .minimal: spacing = -1
  218. case .compact: spacing = 0
  219. case .expanded: spacing = 3
  220. }
  221. let stack = HStack(spacing: spacing) {
  222. Text(bgText)
  223. .strikethrough(context.isStale, pattern: .solid, color: .red.opacity(0.6))
  224. if let direction = directionText {
  225. let text = Text(direction)
  226. switch size {
  227. case .minimal:
  228. let scaledText = text.scaleEffect(x: 0.7, y: 0.7, anchor: .leading)
  229. if let warnColor {
  230. scaledText.foregroundStyle(warnColor)
  231. } else {
  232. scaledText
  233. }
  234. case .compact:
  235. text.scaleEffect(x: 0.8, y: 0.8, anchor: .leading).padding(.trailing, -3)
  236. case .expanded:
  237. text.scaleEffect(x: 0.7, y: 0.7, anchor: .leading).padding(.trailing, -5)
  238. }
  239. }
  240. }
  241. .foregroundStyle(context.isStale ? Color.primary.opacity(0.5) : Color.primary)
  242. return (stack, characters)
  243. }
  244. @ViewBuilder func chart(
  245. context: ActivityViewContext<LiveActivityAttributes>,
  246. additionalState: LiveActivityAttributes.ContentAdditionalState
  247. ) -> some View {
  248. if context.isStale {
  249. Text("No data available")
  250. } else {
  251. // Determine scale
  252. let minValue = min(additionalState.chart.min() ?? 45, 40) - 20
  253. let maxValue = max(additionalState.chart.max() ?? 270, 300) + 50
  254. let yAxisRuleMarkMin = additionalState.unit == "mg/dL" ? additionalState.lowGlucose : additionalState.lowGlucose
  255. .asMmolL
  256. let yAxisRuleMarkMax = additionalState.unit == "mg/dL" ? additionalState.highGlucose : additionalState.highGlucose
  257. .asMmolL
  258. let target = additionalState.unit == "mg/dL" ? additionalState.target : additionalState.target.asMmolL
  259. Chart {
  260. RuleMark(y: .value("Low", yAxisRuleMarkMin))
  261. .lineStyle(.init(lineWidth: 0.5, dash: [5]))
  262. RuleMark(y: .value("High", yAxisRuleMarkMax))
  263. .lineStyle(.init(lineWidth: 0.5, dash: [5]))
  264. RuleMark(y: .value("Target", target)).foregroundStyle(.green.gradient).lineStyle(.init(lineWidth: 1))
  265. ForEach(additionalState.chart.indices, id: \.self) { index in
  266. let currentValue = additionalState.chart[index]
  267. let displayValue = additionalState.unit == "mg/dL" ? currentValue : currentValue.asMmolL
  268. let chartDate = additionalState.chartDate[index] ?? Date()
  269. let pointMark = PointMark(
  270. x: .value("Time", chartDate),
  271. y: .value("Value", displayValue)
  272. ).symbolSize(15)
  273. if displayValue > yAxisRuleMarkMax {
  274. pointMark.foregroundStyle(Color.orange.gradient)
  275. } else if displayValue < yAxisRuleMarkMin {
  276. pointMark.foregroundStyle(Color.red.gradient)
  277. } else {
  278. pointMark.foregroundStyle(Color.green.gradient)
  279. }
  280. }
  281. }
  282. .chartYAxis {
  283. AxisMarks(position: .trailing) { _ in
  284. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.white)
  285. AxisValueLabel().foregroundStyle(.primary).font(.footnote)
  286. }
  287. }
  288. .chartYScale(domain: additionalState.unit == "mg/dL" ? minValue ... maxValue : minValue.asMmolL ... maxValue.asMmolL)
  289. .chartYAxis(.hidden)
  290. .chartPlotStyle { plotContent in
  291. plotContent
  292. .background(
  293. RoundedRectangle(cornerRadius: 12)
  294. .fill(Color.clear)
  295. )
  296. .clipShape(RoundedRectangle(cornerRadius: 12))
  297. }
  298. .chartXAxis {
  299. AxisMarks(position: .automatic) { _ in
  300. AxisGridLine(stroke: .init(lineWidth: 0.2, dash: [2, 3])).foregroundStyle(Color.white)
  301. }
  302. }
  303. }
  304. }
  305. @ViewBuilder func content(context: ActivityViewContext<LiveActivityAttributes>) -> some View {
  306. if let detailedViewState = context.state.detailedViewState {
  307. VStack(content: {
  308. chart(context: context, additionalState: detailedViewState)
  309. .frame(maxWidth: UIScreen.main.bounds.width * 0.9)
  310. .frame(height: 80)
  311. .overlay(alignment: .topTrailing) {
  312. if detailedViewState.isOverrideActive {
  313. HStack {
  314. Text("\(detailedViewState.overrideName)")
  315. .font(.footnote)
  316. .fontWeight(.bold)
  317. .foregroundStyle(.primary)
  318. }
  319. .padding(6)
  320. .background {
  321. RoundedRectangle(cornerRadius: 10)
  322. .fill(Color.purple.opacity(0.6))
  323. }
  324. }
  325. }
  326. HStack {
  327. ForEach(context.state.itemOrder, id: \.self) { item in
  328. switch item {
  329. case "currentGlucose":
  330. if context.state.showCurrentGlucose {
  331. VStack {
  332. bgLabel(context: context, additionalState: detailedViewState)
  333. HStack {
  334. changeLabel(context: context)
  335. if !context.isStale, let direction = context.state.direction {
  336. Text(direction).font(.headline)
  337. }
  338. }
  339. }
  340. }
  341. case "iob":
  342. if context.state.showIOB {
  343. iobLabel(context: context, additionalState: detailedViewState)
  344. }
  345. case "cob":
  346. if context.state.showCOB {
  347. cobLabel(context: context, additionalState: detailedViewState)
  348. }
  349. case "updatedLabel":
  350. if context.state.showUpdatedLabel {
  351. updatedLabel(context: context)
  352. }
  353. default:
  354. EmptyView()
  355. }
  356. Divider().foregroundStyle(.primary).fontWeight(.bold).frame(width: 10)
  357. }
  358. }
  359. })
  360. .privacySensitive()
  361. .padding(.all, 14)
  362. .imageScale(.small)
  363. .foregroundStyle(Color.primary)
  364. .activityBackgroundTint(Color.clear)
  365. } else {
  366. Group {
  367. if context.state.isInitialState {
  368. // add vertical and horizontal spacers around the label to ensure that the live activity view gets filled completely
  369. HStack {
  370. Spacer()
  371. VStack {
  372. Spacer()
  373. expiredLabel()
  374. Spacer()
  375. }
  376. Spacer()
  377. }
  378. } else {
  379. HStack(spacing: 3) {
  380. bgAndTrend(context: context, size: .expanded).0.font(.title)
  381. Spacer()
  382. VStack(alignment: .trailing, spacing: 5) {
  383. changeLabel(context: context).font(.title3)
  384. updatedLabel(context: context).font(.caption).foregroundStyle(.primary.opacity(0.7))
  385. }
  386. }
  387. }
  388. }
  389. .privacySensitive()
  390. .padding(.all, 15)
  391. // Semantic BackgroundStyle and Color values work here. They adapt to the given interface style (light mode, dark mode)
  392. // Semantic UIColors do NOT (as of iOS 17.1.1). Like UIColor.systemBackgroundColor (it does not adapt to changes of the interface style)
  393. // The colorScheme environment varaible that is usually used to detect dark mode does NOT work here (it reports false values)
  394. .foregroundStyle(Color.primary)
  395. .background(BackgroundStyle.background.opacity(0.4))
  396. .activityBackgroundTint(Color.black.opacity(0.4))
  397. }
  398. }
  399. func dynamicIsland(context: ActivityViewContext<LiveActivityAttributes>) -> DynamicIsland {
  400. DynamicIsland {
  401. DynamicIslandExpandedRegion(.leading) {
  402. bgAndTrend(context: context, size: .expanded).0.font(.title2).padding(.leading, 5)
  403. }
  404. DynamicIslandExpandedRegion(.trailing) {
  405. changeLabel(context: context).font(.title2).padding(.trailing, 5)
  406. }
  407. DynamicIslandExpandedRegion(.bottom) {
  408. if context.state.isInitialState {
  409. expiredLabel()
  410. } else if let detailedViewState = context.state.detailedViewState {
  411. chart(context: context, additionalState: detailedViewState)
  412. } else {
  413. Group {
  414. updatedLabel(context: context).font(.caption).foregroundStyle(Color.secondary)
  415. }
  416. .frame(
  417. maxHeight: .infinity,
  418. alignment: .bottom
  419. )
  420. }
  421. }
  422. DynamicIslandExpandedRegion(.center) {
  423. if context.state.detailedViewState != nil {
  424. updatedLabel(context: context).font(.caption).foregroundStyle(Color.secondary)
  425. }
  426. }
  427. } compactLeading: {
  428. bgAndTrend(context: context, size: .compact).0.padding(.leading, 4)
  429. } compactTrailing: {
  430. changeLabel(context: context).padding(.trailing, 4)
  431. } minimal: {
  432. let (_label, characterCount) = bgAndTrend(context: context, size: .minimal)
  433. let label = _label.padding(.leading, 7).padding(.trailing, 3)
  434. if characterCount < 4 {
  435. label
  436. } else if characterCount < 5 {
  437. label.fontWidth(.condensed)
  438. } else {
  439. label.fontWidth(.compressed)
  440. }
  441. }
  442. .widgetURL(URL(string: "Trio://"))
  443. .keylineTint(Color.purple)
  444. .contentMargins(.horizontal, 0, for: .minimal)
  445. .contentMargins(.trailing, 0, for: .compactLeading)
  446. .contentMargins(.leading, 0, for: .compactTrailing)
  447. }
  448. var body: some WidgetConfiguration {
  449. ActivityConfiguration(for: LiveActivityAttributes.self, content: self.content, dynamicIsland: self.dynamicIsland)
  450. }
  451. }
  452. private extension LiveActivityAttributes {
  453. static var preview: LiveActivityAttributes {
  454. LiveActivityAttributes(startDate: Date())
  455. }
  456. }
  457. private extension LiveActivityAttributes.ContentState {
  458. // 0 is the widest digit. Use this to get an upper bound on text width.
  459. // Use mmol/l notation with decimal point as well for the same reason, it uses up to 4 characters, while mg/dl uses up to 3
  460. static var testWide: LiveActivityAttributes.ContentState {
  461. LiveActivityAttributes.ContentState(
  462. bg: "00.0",
  463. direction: "→",
  464. change: "+0.0",
  465. date: Date(),
  466. detailedViewState: nil,
  467. showCOB: true,
  468. showIOB: true,
  469. showCurrentGlucose: true,
  470. showUpdatedLabel: true,
  471. itemOrder: ["currentGlucose", "iob", "cob", "updatedLabel"],
  472. isInitialState: false
  473. )
  474. }
  475. static var testVeryWide: LiveActivityAttributes.ContentState {
  476. LiveActivityAttributes.ContentState(
  477. bg: "00.0",
  478. direction: "↑↑",
  479. change: "+0.0",
  480. date: Date(),
  481. detailedViewState: nil,
  482. showCOB: true,
  483. showIOB: true,
  484. showCurrentGlucose: true,
  485. showUpdatedLabel: true,
  486. itemOrder: ["currentGlucose", "iob", "cob", "updatedLabel"],
  487. isInitialState: false
  488. )
  489. }
  490. static var testSuperWide: LiveActivityAttributes.ContentState {
  491. LiveActivityAttributes.ContentState(
  492. bg: "00.0",
  493. direction: "↑↑↑",
  494. change: "+0.0",
  495. date: Date(),
  496. detailedViewState: nil,
  497. showCOB: true,
  498. showIOB: true,
  499. showCurrentGlucose: true,
  500. showUpdatedLabel: true,
  501. itemOrder: ["currentGlucose", "iob", "cob", "updatedLabel"],
  502. isInitialState: false
  503. )
  504. }
  505. // 2 characters for BG, 1 character for change is the minimum that will be shown
  506. static var testNarrow: LiveActivityAttributes.ContentState {
  507. LiveActivityAttributes.ContentState(
  508. bg: "00",
  509. direction: "↑",
  510. change: "+0",
  511. date: Date(),
  512. detailedViewState: nil,
  513. showCOB: true,
  514. showIOB: true,
  515. showCurrentGlucose: true,
  516. showUpdatedLabel: true,
  517. itemOrder: ["currentGlucose", "iob", "cob", "updatedLabel"],
  518. isInitialState: false
  519. )
  520. }
  521. static var testMedium: LiveActivityAttributes.ContentState {
  522. LiveActivityAttributes.ContentState(
  523. bg: "000",
  524. direction: "↗︎",
  525. change: "+00",
  526. date: Date(),
  527. detailedViewState: nil,
  528. showCOB: true,
  529. showIOB: true,
  530. showCurrentGlucose: true,
  531. showUpdatedLabel: true,
  532. itemOrder: ["currentGlucose", "iob", "cob", "updatedLabel"],
  533. isInitialState: false
  534. )
  535. }
  536. static var testExpired: LiveActivityAttributes.ContentState {
  537. LiveActivityAttributes.ContentState(
  538. bg: "--",
  539. direction: nil,
  540. change: "--",
  541. date: Date().addingTimeInterval(-60 * 60),
  542. detailedViewState: nil,
  543. showCOB: true,
  544. showIOB: true,
  545. showCurrentGlucose: true,
  546. showUpdatedLabel: true,
  547. itemOrder: ["currentGlucose", "iob", "cob", "updatedLabel"],
  548. isInitialState: true
  549. )
  550. }
  551. }
  552. @available(iOS 17.0, iOSApplicationExtension 17.0, *)
  553. #Preview("Notification", as: .content, using: LiveActivityAttributes.preview) {
  554. LiveActivity()
  555. } contentStates: {
  556. LiveActivityAttributes.ContentState.testSuperWide
  557. LiveActivityAttributes.ContentState.testVeryWide
  558. LiveActivityAttributes.ContentState.testWide
  559. LiveActivityAttributes.ContentState.testMedium
  560. LiveActivityAttributes.ContentState.testNarrow
  561. LiveActivityAttributes.ContentState.testExpired
  562. }